Lee Work
Lee Work

Reputation: 53

Python: recording works, but only once then I must restart the script

basically what I am trying to do is record audio (using pyaudio) for a few seconds and save it, it works fine no problem except after recording for 3 seconds it will keep the mic in use for almost a minute and I cant record in the mean time I will get an error. The code is below. Thank you in advance for any answers.

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()

This is the error I get when pressing the button after the first recording, also the recording uses a thread not sure if that will matter to the question, thats why there is sys exit() at the end of the function.

    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

EDIT: The script will only work once, after that the program must be restarted or that error above will appear so it might not be a problem with the mic being in use by the program.

Upvotes: 2

Views: 1082

Answers (1)

Lee Work
Lee Work

Reputation: 53

The answer was quite simple, instead of using p as a global variable I used it as a local variable like so:

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()

Upvotes: 2

Related Questions