Python, Error audio Recording in 16000Hz using Pya

2020-06-17 14:05发布

问题:

I use Python 2.7.3, Mac OS 10.8.2 and Xcode 4.5.1

I am trying to record sound using PyAudio following the instructions in http://people.csail.mit.edu/hubert/pyaudio/

and using the program

"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

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

It works well with RATE = 44100. But I want to record with RATE = 16000 and CHANNELS = 1

Changing the values give me an error as

How will I be able to record with RATE = 16000?

回答1:

I experienced the same problem. The issue was fixed in portaudio, but brew installed an old version for me. I upgraded with

brew install portaudio --HEAD

and then was able to run your code with CHANNELS=1 and RATE=16000