Python PyAudio库适用于多种开发环境,包括Windows、macOS和Linux操作系统。以下是其相关介绍:
Windows:
pip install pyaudio
。如果遇到权限问题,可以尝试使用管理员权限运行命令提示符。macOS:
brew install portaudio
。pip install pyaudio
。Linux:
sudo apt-get install portaudio19-dev
pip3 install pyaudio
sudo dnf install portaudio-devel
pip3 install pyaudio
```。
以下是一个简单的Python脚本示例,展示了如何使用PyAudio库进行音频录制和播放:
录音示例:
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("开始录音...")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS))):
data = stream.read(CHUNK)
frames.append(data)
print("录音结束!")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
播放示例:
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data:
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
通过上述步骤和示例代码,您可以在不同的开发环境中成功使用PyAudio库进行音频处理。