无法多次录制语音

Can't record voice more than once

我试图创建一个函数来记录我的声音以利用语音识别系统,但是下面的函数在程序执行中只工作一次,如果调用多次就会出错。我该如何克服这个问题?

这里是录音功能:

def recordVoice(FORMAT, channels, sample_rate, input, output, chunk):
    # 5 seconds voice recording
    stream = p.open(format=FORMAT,
                channels=channels,
                rate=sample_rate,
                input=True,
                output=True,
                frames_per_buffer=chunk)

    frames = []
    print("Recording...")
    for i in range(int(sample_rate / chunk * record_seconds)):
        data = stream.read(chunk)
        # if you want to hear your voice while recording
        # stream.write(data)
        frames.append(data)
    print("Finished recording.")
    # stop and close stream
    stream.stop_stream()
    stream.close()
    # terminate pyaudio object
    p.terminate()
    # save audio file
    # open the file in 'write bytes' mode
    wf = wave.open(RECORDED_AUDIO, "wb")
    # set the channels
    wf.setnchannels(channels)
    # set the sample format
    wf.setsampwidth(p.get_sample_size(FORMAT))
    # set the sample rate
    wf.setframerate(sample_rate)
    # write the frames as bytes
    wf.writeframes(b"".join(frames))
    # close the file
    wf.close()

这里是我如何使用这个函数的:

recordVoice(FORMAT, channels, sample_rate, True, True, chunk)
trimAudio.trimAudio(1, 'rawAudio.wav')
pn = Predict_Number()
device = pn.predict('trimedAudio.wav')
fullPhrase += device + " "
print(fullPhrase)

# Get action to perform
print("Do you want to turn the device on or off?")
recordVoice(FORMAT, channels, sample_rate, True, True, chunk)
trimAudio.trimAudio(1, 'rawAudio.wav')
pa = Predict_Action()
action = pa.predict('trimedAudio.wav')
fullPhrase += action

这是我得到的错误:

Traceback (most recent call last):
  File "client.py", line 82, in <module>
    recordVoice(FORMAT, channels, sample_rate, True, True, chunk)
  File "client.py", line 29, in recordVoice
    stream = p.open(format=FORMAT,
  File "C:\AppData\Local\Programs\Python\Python38\lib\site-packages\pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "C:\AppData\Local\Programs\Python\Python38\lib\site-packages\pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9996] Invalid output device (no default output device)

通过注释行

stream.stop_stream()
stream.close()

我能够在没有程序崩溃的情况下录制多个语音。我认为停止和关闭流是主要问题。