Skip to main content
 首页 » 编程设计

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

2024年10月25日8mayingbao

基本上我想做的是录制音频(使用 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()