pyaudio可以快速完成录音,播放等功能,但是安装,书写时遇到相当多的问题
pyaudio可以支持Python2,也可以支持Python3
需要根据需要安装不同的版本
链接地址
https://people.csail.mit.edu/hubert/pyaudio/packages/
cpXX表示支持的Python版本,根据需要下载,
mac电脑安装,必须先安装依赖库portaudio
Python2版本
brew install portaudio
pip install pyaudio
python3版本
brew install portaudio
pip3 install pyaudio
代码示例
#录制音频
import pyaudio
import wave
chunk = 1024 # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16 # 16 bits per sample
channels = 2
fs = 44100 # Record at 44100 samples per second
seconds = 3
filename = "output.wav"
p = pyaudio.PyAudio() # Create an interface to PortAudio
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = [] # Initialize array to store frames
# Store data in chunks for 3 seconds
for i in tqdm(range(0, int(fs / chunk * seconds))):
data = stream.read(chunk)
frames.append(data)
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()
print('Finished recording')
# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
此时出现错误[Errno -9998] Invalid number of channels
经过排查是由于电脑采集的频道为1,而不是2 ,1是麦克风
所以将channels改成channels =1
运行后效果如图:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。