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.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
UnkwnTech
  • 88,102
  • 65
  • 184
  • 229

4 Answers4

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.

Jeffrey Martinez
  • 4,384
  • 2
  • 31
  • 36
  • 1
    "Note that PyAudio currently only supports blocking-mode audio I/O. PyAudio is still super-duper alpha quality." from website – Dustin Getz Jul 23 '09 at 18:20
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.

Serafina Brocious
  • 30,433
  • 12
  • 89
  • 114
  • 3
    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 – Jared Apr 10 '09 at 04:51
2

You might try SWMixer.

Bill Barksdale
  • 2,466
  • 1
  • 14
  • 6
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.

icedwater
  • 4,701
  • 3
  • 35
  • 50