无法使用 pyaudio 录制多个波形(无默认输出设备)

Can't record more than one wave with pyaudio (no default output device)

我正在尝试编写最简单的程序来录制两个录音并录制两个波形文件。您可以获得原始代码:https://gist.github.com/579095ac89fa2fff58db

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()

def record(file_name):

  stream = p.open(format = FORMAT,
    channels = CHANNELS,
    rate = RATE,
    input = True,
    frames_per_buffer = CHUNK)

  frames = []
  print "starting recording " + file_name + "."
  for i in range(0, int(RATE / CHUNK * 2)):
    data = stream.read(CHUNK)
    frames.append(data)
  print "finished recording"

  stream.stop_stream()
  stream.close()
  p.terminate()

  wf = wave.open(file_name, 'wb')
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  wf.writeframes(b''.join(frames))
  wf.close()

record('first.wav')
# try again
record('second.wav')

如果我只调用一次记录函数,一切正常,但如果我再次尝试调用它,我会得到:IOError: [Errno -9996] Invalid input device (no default output device).

python record2x.py
starting recording first.wav.
finished recording
Traceback (most recent call last):
  File "record2x.py", line 38, in <module>
    record('second')
  File "record2x.py", line 16, in record
    frames_per_buffer = CHUNK)
  File "/usr/local/lib/python2.7/site-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
IOError: [Errno -9996] Invalid input device (no default output device)

我过早地终止了直播。我只需要删除终止调用。

没什么奇怪的。你在你的函数中调用了 p.terminate() 意味着你完全解雇了 PyAudio。所以它与声卡分离并等待新的初始化。 p.terminate() 仅在程序退出时调用。 此外,在这里,在您的函数中, stream.stop_stream() 是不必要的,因为 stream.close() 可以解决问题。除非您稍后在启动某些音频时遇到一些点击,但这可能只是在使用 output=True 时,而不是 input=True