我正在尝试编写最简单的程序来拍摄两张录音并录制两张wave文件。您可以获取原始代码:https://gist.github.com/579095ac89fa2fff58db
import pyaudio import wave CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() def record(file_name): stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = CHUNK) frames = [] print "starting recording " + file_name + "." for i in range(0, int(RATE / CHUNK * 2)): data = stream.read(CHUNK) frames.append(data) print "finished recording" stream.stop_stream() stream.close() p.terminate() wf = wave.open(file_name, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() record('first.wav') # try again record('second.wav')
如果我只调用一次记录函数,一切正常,但是如果我再次调用它,我得到:IOError:[Errno -9996]输入设备无效(没有默认输出设备)。
python record2x.py
starting recording first.wav.
finished recording
Traceback (most recent call last):
File "record2x.py", line 38, in <module>
record('second')
File "record2x.py", line 16, in record
frames_per_buffer = CHUNK)
File "/usr/local/lib/python2.7/site-packages/pyaudio.py", line 750, in open
stream = Stream(self, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/pyaudio.py", line 441, in __init__
self._stream = pa.open(**arguments)
IOError: [Errno -9996] Invalid input device (no default output device)
答案 0 :(得分:1)
我过早地终止了流。我只需要删除终止呼叫。
答案 1 :(得分:1)
没什么奇怪的。你在函数中调用p.terminate()意味着你完全解雇了PyAudio。所以它脱离了声卡并等待新的初始化。 p.terminate()仅在退出程序时调用。 此外,在这里,在你的功能。 stream.stop_stream()是不必要的,因为stream.close()会做到这一点。除非您在稍后启动某些音频时遇到一些点击,但这可能只是在使用output = True时,而不是input = True。