10

Can I access a users microphone in Python?

Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.

2

4 Answers 4

18

I got the job done with pyaudio

It comes with a binary installer for windows and there's even an example on how to record through the microphone and save to a wave file. Nice! I used it on Windows XP, not sure how it will do on Vista though, sorry.

Sign up to request clarification or add additional context in comments.

1 Comment

"Note that PyAudio currently only supports blocking-mode audio I/O. PyAudio is still super-duper alpha quality." from website
4

Best way to go about it would be to use the ctypes library and use WinMM from that. mixerOpen will open a microphone device and you can read the data easily from there. Should be very straightforward.

1 Comment

Do you think you can provide some sample code for this? I can call mixerGetNumDevs but i'm not sure how to get from there to mixerOpen or for reading levels. TIA
2

You might try SWMixer.

Comments

1

Just as an update to Martinez' answer above, I also used pyAudio (latest edition is 0.2.13 since Dec 26 2022).

Here's how to install pyaudio on windows (I did it in a virtual environment):

pip install pyaudio   # as of python 3.10 this should download a wheel

Once you have it installed, assuming you want to record into a 16-bit wave file, this snippet adapted from the documentation should help:

import wave      # this will probably also need to be installed
import pyaudio

RATE = 16000
FORMAT = pyaudio.paInt16 # 16-bit frames, ie audio is in 2 bytes
CHANNELS = 1             # mono recording, use 2 if you want stereo
CHUNK_SIZE = 1024        # bytes
RECORD_DURATION = 10     # how long the file will be in seconds

with wave.open("recording.wav", "wb") as wavefile:
    p = pyaudio.PyAudio()
    wavefile.setnchannels(CHANNELS)
    wavefile.setsampwidth(p.get_sample_size(FORMAT))
    wavefile.setframerate(RATE)

    stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True)
    for _ in range(0, RATE // CHUNK_SIZE * RECORD_DURATION):
        wavefile.writeframes(stream.read(CHUNK_SIZE))
    stream.close()

    p.terminate()

I wasn't able to use with for the stream handler, but this might be possible in future editions of pyAudio.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.