I use read() in a tight loop where I write microphone data to a file using python-soundfile. I've found it helpful to create a version of the read function that takes a preallocated numpy buffer, so I can write code like this:
import soundfile
import numpy as np
# Open alsa device
adevice = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device=device)
self.adevice.setchannels(num_channels)
self.adevice.setrate(fs)
scale_factor = 4 # system fixed number of buffers
if dtype == 'int16':
adevice.setformat(alsaaudio.PCM_FORMAT_S16_LE)
scale_factor = scale_factor*2
else:
raise(ValueError("dtypes other than 'int16' not currently supported."))
adevice.setperiodsize(self.buffer_size)
in_buf = np.zeros((buffer_size*scale_factor, channels), dtype=dtype, order='C')
with soundfile.SoundFile(soundfilename, 'w', fs, channels, 'PCM_16') as soundfile:
while True:
nsamp = adevice.read_into(in_buf)
self.soundfile.write(in_buf[:nsamp,:])
if nsamp < buffer_size:
print('ALSA Read buffer underrun.')
The two caveats about the proposedread_into() are (1) dependency on numpy and (2) I only have working Python 3 code.
I use read() in a tight loop where I write microphone data to a file using python-soundfile. I've found it helpful to create a version of the read function that takes a preallocated numpy buffer, so I can write code like this:
The two caveats about the proposed
read_into()are (1) dependency on numpy and (2) I only have working Python 3 code.