Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio Recording in Python

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?

like image 593
jsj Avatar asked Jul 29 '11 01:07

jsj


People also ask

How do I record audio from a python script?

The python-sounddevice and pyaudio libraries provide ways to record audio with Python. python-sounddevice records to NumPy arrays and pyaudio records to bytes objects. Both of these can be stored as WAV files using the scipy and wave libraries, respectively.

How to record audio using pyaudio?

It also provides Python bindings for PortAudio, the cross-platform audio I/O library as provided by python-sounddevice. With PyAudio, you can easily use Python to play and record audio on a variety of platform. Use Up/Down Arrow keys to increase or decrease volume. Now just switching to the recording mode of the article.

How do I play a sound file in Python?

playsound is a “pure Python, cross platform, single function module with no dependencies for playing sounds.” With this module, you can play a sound file with a single line of code: from playsound import playsound playsound('myfile.wav')

What is the best library for playing audio files in Python?

Pydub is quite a popular library, as it isn't only for playing sound, you can use it for different purposes, such as converting audio files, slicing audio, boosting or reducing volume, and much more, check their repository for more information. If you wish to play audio using PyAudio, check this link.


1 Answers

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)
like image 103
maxy Avatar answered Sep 20 '22 13:09

maxy