9

I want to record short audio clips from a USB microphone in Python. I have tried pyaudio, which seemed to fail communicating with ALSA, and alsaaudio, the code example of which produces an unreadable files.

So my question: What is the easiest way to record clips from a USB mic in Python?

jsj
  • 9,019
  • 17
  • 58
  • 103
  • possible duplicate of [Detect & Record Audio in Python](http://stackoverflow.com/questions/892199/detect-record-audio-in-python) – S.Lott Jul 29 '11 at 02:03
  • I have used PyGStreamer for it and it worked well but I cannot really say that it is the solution to your question. – brandizzi Jul 29 '11 at 02:07
  • On Windows, alsaaudio did not appear to be a viable option because the default pip install wanted vsstudio so it could compile from source. The [Detect & Record Audio in Python](https://stackoverflow.com/questions/892199/detect-record-audio-in-python) mentioned earlier lead me to pyaudio, which worked well for me. Again, this is all on Windows, but I think the OP here is talking about Linux. – Josiah Yoder Aug 23 '22 at 19:29

1 Answers1

13

This script records to test.wav while printing the current amplitute:

import alsaaudio, wave, numpy

inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1024)

w = wave.open('test.wav', 'w')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)

while True:
    l, data = inp.read()
    a = numpy.fromstring(data, dtype='int16')
    print numpy.abs(a).mean()
    w.writeframes(data)
maxy
  • 4,971
  • 1
  • 23
  • 25
  • coulnd't you use `array.array('h', data)` or `struct` instead of numpy? – Erik Kaplun Sep 29 '13 at 16:04
  • 1
    I mainly get audio into Python to do signal processing. For that you want numpy. For simple recording I would just use a command line tool like 'arecord'. In Python I can do FFT and check if a certain frequency is dominant with just three lines of code or so. – maxy Oct 01 '13 at 10:45
  • 1
    Someone verify this and comment whether it works.. it's been ages since I asked this and I should really accept something. – jsj May 26 '16 at 11:36