Error recording audio using pyaudio - IOError: [Errno -9997]

0

I'm trying to write an audio from a script I developed with python using pyaudio but I'm encountering a strange error, below is the script that was saved with the name rec.py:

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

The script works fine, but when I try to run with "sudo" it gives me the error below:

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

If I run without sudo, that works fine.

So far so good I could run without the sudo, but the purpose of this script is to put it to run inside a bash script as a service. apparently the linux executes the services with the "sudo" and the same error occurs:

Has anyone ever faced this problem? Could you tell me how I can solve it?

    
asked by anonymous 13.12.2018 / 22:09

0 answers