Python pyaudio

From wikinotes

Documentation

official docs http://people.csail.mit.edu/hubert/pyaudio/docs/
port-audio official docs http://portaudio.com/docs/v19-doxydocs/index.html
realpython tut, various audio modules https://realpython.com/playing-and-recording-sound-python/
portaudio - writing callback http://portaudio.com/docs/v19-doxydocs/writing_a_callback.html

Concepts

rate:          44100   # 44100 Hz (44100 recorded frames/second)
channels:      2       # 2-channels (stereo)
sample-width:  2       # ?

Usage

Choosing Device

pyaudio will use your system to determine default devices, but you can have a little more control

# init portaudio system
pa = pyaudio.PyAudio()

# list devices by name, with the max number of 
# input/output (record/playback) channels they support
for i in range(pa.get_device_count()):
    device_info = pa.get_device_info_by_index(i)
    print('{name}: in:{maxInputChannels} out:{maxOutputChannels}'.format(**device_info))

Recording

import pyaudio
import wave


# init portaudio system
pa = pyaudio.PyAudio()

# =========
# record 1s
# =========
stream_in = pa.open(
    rate=44100,                          # 44100 Hz (44100 frames/second)
    channels=2,                          # 2-channels (stereo)
    format=pa.get_format_from_width(2),  # sample-width of 2
    input=True,                          # we are recording on this stream
    frames_per_buffer=1024,              # get new read-buffer every N frames
)
try:
    raw_wav_data = stream_in.read(num_frames=44100)
    print(raw_wav_data)
finally:
    stream_in.stop_stream()
    stream_in.close()


# =============
# write to file
# =============
wav_file = wave.open('/var/tmp/audio.wav', 'wb')
wav_file.setframerate(44100.0)
wav_file.setnchannels(2)
wav_file.setsampwidth(2)
wav_file.writeframes(raw_wav_data)