Python:录制工作,但只有一次,我必须重新启动脚本

时间:2014-09-16 10:28:53

标签: python python-2.7 python-2.x pyaudio

基本上我要做的是录制音频(使用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()的原因。 / p>

    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

编辑:该脚本只能运行一次,之后必须重新启动程序或出现上述错误,因此程序正在使用麦克风可能不会出现问题。

1 个答案:

答案 0 :(得分:2)

答案很简单,而不是使用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()