使用pyaudio录制音频时出错-IOError:[Errno -9997]

时间:2018-12-14 16:03:27

标签: python audio recording pyaudio

我遇到一个奇怪的错误。我在下面制作脚本,用于通过麦克风录制音频:

import pyaudio
import wave
import sys

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = int(sys.argv[2])
WAVE_OUTPUT_FILENAME = sys.argv[1]

#RECORD_SECONDS = 7
#WAVE_OUTPUT_FILENAME = "output.wav"
print RECORD_SECONDS
print WAVE_OUTPUT_FILENAME

p = pyaudio.PyAudio()

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

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

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

当我使用“ sudo”运行时,出现此错误:

sudo python rec.py“ test.mp3” 5

Expression 'PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer, &inputLatency, &outputLatency, &hostBufferSizeMode )' 
failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2843
Traceback (most recent call last):
  File "rec.py", line 26, in <module>
    frames_per_buffer=CHUNK)
  File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
IOError: [Errno -9997] Invalid sample rate

但是如果我在没有“ sudo”的情况下运行,则脚本可以正常工作。

这个想法是在启动linux(etc / rc.local)中运行这个脚本(rec.py),我创建了一个bash脚本并放置了代码:

#!/bin/sh
python /home/script/rec.py "/home/out/test.mp3" 5

在这种情况下,我遇到了与“ sudo”相同的错误

谁知道我该如何解决?

0 个答案:

没有答案