Audio Recording in Python
Asked Answered
E

1

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?

Expiration answered 29/7, 2011 at 1:22 Comment(3)
possible duplicate of Detect & Record Audio in PythonRiarial
I have used PyGStreamer for it and it worked well but I cannot really say that it is the solution to your question.Sailfish
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 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.Evangelical
A
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)
Atreus answered 29/7, 2011 at 5:15 Comment(5)
coulnd't you use array.array('h', data) or struct instead of numpy?Bolanos
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.Atreus
Someone verify this and comment whether it works.. it's been ages since I asked this and I should really accept something.Expiration
Answer is from 2011, code needs to be edited for python3.Dermatology
To my surprise this still works. I only had to add brackets for the print. Maybe there is a more modern or easier library today. If you know please add an answer!Atreus

© 2022 - 2024 — McMap. All rights reserved.