Time audio processing in Python

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?

链接地址: http://www.djcxy.com/p/33830.html

上一篇: 根据频率响应计算FIR系数

下一篇: Python中的时间音频处理