欢迎访问宙启技术站
智能推送

Python中的PyAudio简介和基本用法

发布时间:2024-01-09 09:11:38

PyAudio是一个用于Python的音频处理库,提供了录制、播放和处理音频的功能。它基于PortAudio库,可以在不同的平台上实现音频的输入和输出。

PyAudio的基本用法如下:

1. 安装PyAudio库

可以使用pip命令安装PyAudio库:

pip install pyaudio

2. 导入PyAudio库

导入PyAudio库,以便在代码中使用其功能:

import pyaudio

3. 创建PyAudio对象

创建PyAudio对象,用于进行音频输入和输出的操作:

pa = pyaudio.PyAudio()

4. 获取设备信息

使用get_device_info_by_index()方法获取系统中可用的音频设备信息:

device_info = pa.get_device_info_by_index(device_index)

5. 打开音频流

使用open()方法打开音频输入或输出流:

stream = pa.open(format = pa.get_format_from_width(width),
                channels = channels,
                rate = sample_rate,
                input = True,
                output = True,
                frames_per_buffer = chunk)

6. 读取音频

使用stream.read()方法读取音频流中的数据,可以指定读取的帧数:

data = stream.read(chunk)

7. 写入音频

使用stream.write()方法将音频数据写入音频输出流:

stream.write(data)

8. 录制音频

通过将input参数设置为True,可以录制音频数据:

stream = pa.open(format = pa.get_format_from_width(width),
                channels = channels,
                rate = sample_rate,
                input = True,
                frames_per_buffer = chunk)
data = stream.read(chunk)

9. 播放音频

通过将output参数设置为True,可以播放音频数据:

stream = pa.open(format = pa.get_format_from_width(width),
                channels = channels,
                rate = sample_rate,
                output = True,
                frames_per_buffer = chunk)
stream.write(data)

10. 停止音频流

使用stream.stop_stream()方法停止音频流的读取或写入:

stream.stop_stream()

11. 关闭音频流

使用stream.close()方法关闭音频流:

stream.close()

12. 关闭PyAudio对象

使用pa.terminate()方法关闭PyAudio对象:

pa.terminate()

下面是一个使用PyAudio录制声音并保存为WAV文件的例子:

import pyaudio
import wave

chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
rate = 44100
record_seconds = 5
output_filename = "output.wav"

pa = pyaudio.PyAudio()

stream = pa.open(format=sample_format,
                channels=channels,
                rate=rate,
                frames_per_buffer=chunk,
                input=True)

frames = []

for i in range(0, int(rate / chunk * record_seconds)):
    data = stream.read(chunk)
    frames.append(data)

stream.stop_stream()
stream.close()

pa.terminate()

wave_file = wave.open(output_filename, 'wb')
wave_file.setnchannels(channels)
wave_file.setsampwidth(pa.get_sample_size(sample_format))
wave_file.setframerate(rate)
wave_file.writeframes(b''.join(frames))
wave_file.close()

总结:

PyAudio是一个功能强大的音频处理库,可以实现音频的录制、播放和处理功能。通过创建一个PyAudio对象,可以打开音频流并读取或写入音频数据。使用PyAudio可以简单地录制声音、播放声音或对声音进行处理,是一个非常实用的音频处理工具。