I'm trying to record data from my microphone and then play it back through the speakers in real time, and with some delays, but I'm having some problems with it. I chose to use python and alsaaudio, and my current script I'm having problems with can be found here. This works with what I have this far(not the delay part), but produces some clicking. alsaaudio docs has this to say:
The most common reason for problems with playback of PCM audio is that writes to PCM devices must exactly match the data rate of the device.
If too little data is written to the device, it will underrun, and ugly clicking sounds will occur. Conversely, of too much data is written to the device, the write function will either block (PCM_NORMAL mode) or return zero (PCM_NONBLOCK mode).
I seem to be misunderstanding the docs, it says this about write():
PCM.write(data)
Writes (plays) the sound in data. The length of data must be a multiple of the frame size, and should be exactly the size of a period
a period in my script is 160.
it says this about read():
In PCM_NORMAL mode, this function blocks until a full period is available, and then returns a tuple (length,data) where length is the number of frames of captured data, and data is the captured sound frames as a string. The length of the returned data will be periodsize*framesize bytes.
in my script, period_size*frame_size should also be equal to 160, but when I print the length(part of tuple read() returns) i'm getting 940. Obviously I seem to not be passing the right amount of data to out.write(), but I'm not sure where to go. I put this code together mostly through examples I found, and I just started working with alsaaudio / sound, trying to put together some interesting projects, so I don't know a whole lot yet.
I also wanted to record live from the microphone, then playback with a 100ms delay, hence the commented time.sleep(). If I uncomment it, the length seems to go from 940 to -32 repeatedly, eventually causing out.write() to throw an exception (not enough data).
Could someone tell me how (or what's wrong with my script) I'd go about recording and playing back sound data in real time, and with a 100ms delay?