PyAudio录制花费的时间比计划的长得多

时间:2019-09-24 13:53:55

标签: python pyaudio

我正在尝试使用PyAudio录制块中的声音15秒钟,块大小为1024,采样率为1024 * 40。我知道块的数量为(记录时间)*(采样率)/(块大小)。

但是,当我为for循环完成所需的时间时,它比15秒要长得多,比预期的要长3倍左右。我想知道为什么?当然,我在每个循环中都有一个滞后来显示每个块的FFT,但这仅是0.001秒。

这是因为Windows不是实时系统吗?

import time
import image
import numpy as np
import os
import pyaudio
import matplotlib.pyplot as plt
from scipy.fftpack import fft


CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 1024*40
RECORD_SECONDS = 15

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

input('Press key to start recording:\n')
print('2 sec delay started')
time.sleep(2)
print("* recording")

n = CHUNK
k=np.arange(n)
T = n/RATE #reciprocal of freq resolution
frq = k/T #k* freq resolution for plotting
window=np.hanning(n) #apply Hanning window to minimize spectrum leakage
num_frames=int(RATE*RECORD_SECONDS/CHUNK)

for i in range(0, num_frames):
    data = stream.read(CHUNK)
    decoded = np.frombuffer(data, dtype=np.int16)
    #decoded= decoded/2**15
    windowed=window*decoded
    fft_decode=fft(windowed)/(len(decoded)/2)
    mags=np.absolute(fft_decode)

    plt.ylim(top=200)
    plt.xlabel('Freq (Hz)')
    plt.ylabel('|Y(freq)|')
    plt.plot(frq[range(int(n/2))], mags[range(int(n/2))],'b') 
    plt.pause(.001)
    plt.gcf().clear()


print("* done recording")
plt.close()

0 个答案:

没有答案