我正在使用Pyaudio同时播放和录制wav文件。我在Ubuntu 16.04上使用Python 2.7.12。主要步骤是:
这是我的代码:
chunk1 = 2048
chunk2 = 2048
format_ = pyaudio.paInt16
wf = wave.open(file_, 'rb')
p1 = pyaudio.PyAudio()
p2 = pyaudio.PyAudio()
# stream1 for playing the wav file
stream1 = p1.open(format=format_,
channels=1,
rate=16000,
output=True,
frames_per_buffer=chunk1)
# stream1 for recording the sound coming from speaker
stream2 = p2.open(format=format_,
channels=1,
rate=16000,
input=True,
frames_per_buffer=chunk2)
frames1 = []
frames2 = []
stream1.start_stream()
data_read = wf.readframes(chunk1)
while data_read != '':
# play wav part
stream1.write(data_read)
data_read = wf.readframes(chunk1)
temp1 = np.fromstring(data_read)
print "source:", temp1.shape
frames1.append(data_read)
# record sound part
data_write = stream2.read(chunk2)
temp2 = np.fromstring(data_write)
print "recorded:", temp2.shape
frames2.append(data_write)
stream1.stop_stream()
stream1.close()
p1.terminate()
stream2.stop_stream()
stream2.close()
p2.terminate()
wf1 = wave.open('input.wav', 'wb')
wf1.setnchannels(wf.getnchannels())
wf1.setsampwidth(p1.get_sample_size(format_))
wf1.setframerate(wf.getframerate())
wf1.writeframes(b''.join(frames1))
wf1.close()
wf2 = wave.open('output.wav', 'wb')
wf2.setnchannels(wf.getnchannels())
wf2.setsampwidth(p2.get_sample_size(format_))
wf2.setframerate(wf.getframerate())
wf2.writeframes(b''.join(frames2))
wf2.close()
我这样做有些困难。我得到的错误如下:
source: (512,)
recorded: (512,)
source: (512,)
ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
recorded: (512,)
source: (512,)
ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
recorded: (512,)
ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
source: (512,)
ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
recorded: (512,)
source: (512,)
recorded: (512,)
ALSA lib pcm.c:7963:(snd_pcm_recover) underrun occurred
我也不明白为什么必须将chunk = 2048
设置为frame = 512
。
你能帮我解决这个问题吗?如果有人有其他建议,请告诉我。
当我发布这个问题时,我无法打开PyAudio文档:
https://people.csail.mit.edu/hubert/pyaudio/docs/
该网站已关闭。
干杯。