不能多次录制语音

2024-09-30 01:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数来记录我的声音,以便使用语音识别系统,但下面的函数在程序执行时只工作一次,如果调用多次,则会出现错误。我怎样才能克服这个问题

以下是语音记录功能:

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)

Tags: thesampleintrueformatoutputstreamframes

热门问题