0

I'm trying to write a program for analyzing chunks of audio recorded by my computer. I would like to be able to seperate the audio into chunks that are about 5 seconds long (220500 samples or so) and if there isn't 5 seconds worth of samples available, just take whatever is left (eg if recording for 32 seconds, I'd like to seperate the stream into 6 segments that are 5 seconds long and a final segment that is 2 seconds long). I'm using Pyaudio to record audio

stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
          input_device_index=1, output_device_index=6,frames_per_buffer=1500, stream_callback = callback)

with a callback function that is called every 1500 samples. The callback function checks if audio is present and if so, writes the 1500 samples to a queue.

q = Queue.Queue()
def callback(in_data, frame_count, time_info, status):
    in_data = array('h', in_data)
    if is_silent(in_data) == False:
        in_data = trim(in_data)
        in_data = np.fromstring(in_data, dtype=np.int16)
        q.put(in_data)
    return (in_data, pyaudio.paContinue)

After Audio has been detected, my program enters the following loop:

r = array('h')
while 1:
    if q.empty() == False:
        snd_data = q.get()
        r.extend(snd_data)

    if len(r) > 220500 or q.empty() == True:
        print len(r)
        r = []
        r = array('h')

I would like the while loop to run until the queue is empty and check in the if statement if approx 5 seconds of audio data has been recorded and is present in r. If the queue is empty I would like to just analyse whatever is left in r (in this case, just print whatever is left to the screen) before ending the loop but I'm having trouble making a loop that can do this without ending early or running indefinitely. Does anyone have any ideas how I can alter the code to meet my objectives?

CJF
  • 51
  • 1
  • 3
  • I don't know Pyaudio. Does your `callback` have any way to determine that there won't be any more data to put on the queue? – PM 2Ring Aug 11 '17 at 10:37
  • Not really, the only thing I can do is check if in_data is silent, and if so, leave it off the queue. – CJF Aug 11 '17 at 10:45
  • When there's no more audio data does the callback get sent blocks of silence, or does it just sit there waiting forever? If it still gets called, it could check the system time and if there's only been silence for a given time period it could then signal that there's no more data, eg it could set an [Event](https://docs.python.org/2/library/threading.html#event-objects), or simply put a special data value on the queue, like `None`. – PM 2Ring Aug 11 '17 at 11:05

0 Answers0