基本上我想做的是录制音频(使用 pyaudio)几秒钟并保存它,它工作正常没有问题,除了录制 3 秒后它会让麦克风使用近一分钟,我不能同时记录我会得到一个错误。代码如下。预先感谢您的任何答复。
def startrecordingnow():
print ("Recording Now")
global p
stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * 3)):
data = stream.read(CHUNK)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
progress.stop()
print ("Not recording anymore")
saveandsend("None")
sys.exit()
这是我在第一次录制后按下按钮时遇到的错误,而且录制使用了一个线程,不确定这是否对问题重要,这就是为什么函数末尾有 sys exit() 的原因。
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\Liam\Desktop\NXT-Python\examples\voice-recognition.py", line 70, in startrecordingnow
stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
File "C:\Python27\lib\site-packages\pyaudio.py", line 747, in open
stream = Stream(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\pyaudio.py", line 442, in __init__
self._stream = pa.open(**arguments)
IOError: [Errno Invalid input device (no default output device)] -9996
编辑:该脚本只能运行一次,之后必须重新启动程序,否则将出现上述错误,因此程序使用的麦克风可能不是问题。
最佳答案
答案非常简单,我没有使用 p 作为全局变量,而是将其用作局部变量,如下所示:
def startrecordingnow():
print ("Recording Now")
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE / CHUNK * 3)):
data = stream.read(CHUNK)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
progress.stop()
print ("Not recording anymore")
saveandsend("None")
sys.exit()
关于Python:记录有效,但只有一次,然后我必须重新启动脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25866398/