I was trying to create a function to record my voice to make use of a speech recognition system, but the function below only works once in program execution and gives an error if it is called more than once. How can I overcome this problem?
Here is the voice recording function:
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()
Here how I use the function:
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
And here is the error I get:
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)
By commenting the lines
stream.stop_stream()
stream.close()
I was able to record voice more than one without program crashing. I think stopping and closing the stream was the main prbolem.