要使用PyAudio,首先使用 pyaudio.PyAudio()
(1)实例化PyAudio ,它设置portaudio系统。
要录制或播放音频,请使用 pyaudio.PyAudio.open()
(2)在所需设备上打开所需音频参数的流。这设置了 pyaudio.Stream 播放或录制音频。
通过使用流式传输 pyaudio.Stream.write() 音频数据或使用流式传输音频数据来播放音频 pyaudio.Stream.read() 。
(3)请注意,在“阻止模式”中,每个 pyaudio.Stream.write() 或 pyaudio.Stream.read() 阻止直到所有给定/请求的帧都被播放/记录。或者,要动态生成音频数据或立即处理录制的音频数据,请使用下面概述的“回调模式”。
使用 pyaudio.Stream.stop_stream() 暂停播放/录制,并 pyaudio.Stream.close() 终止流。
(4)最后,使用 pyaudio.PyAudio.terminate()
(5)终止portaudio会话
1).采集音频import pyaudio
import wave
from tqdm import tqdm
def record_audio(wave_out_path,record_second):
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
wf = wave.open(wave_out_path, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
print("* recording")
for i in tqdm(range(0, int(RATE / CHUNK * record_second))):
data = stream.read(CHUNK)
wf.writeframes(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
record_audio("output.wav",record_second=4)
2).播放音频
通过tqdm,显示播放进度条"""PyAudio Example: Play a WAVE file."""
import pyaudio
import wave
from tqdm import tqdm
def play_audio(wave_path):
CHUNK = 1024
wf = wave.open(wave_path, 'rb')
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
# open stream (2)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
# read data
data = wf.readframes(CHUNK)
# play stream (3)
datas = []
while len(data) > 0:
data = wf.readframes(CHUNK)
datas.append(data)
for d in tqdm(datas):
stream.write(d)
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
play_audio("output.wav")
3).以回调方式播放音频"""PyAudio Example: Play a WAVE file."""
import pyaudio
import wave
from tqdm import tqdm
import time
def play_audio_callback(wave_path):
CHUNK = 1024
wf = wave.open(wave_path, 'rb')
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
return (data, pyaudio.paContinue)
# open stream (2)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True,
stream_callback=callback)
# read data
stream.start_stream()
while stream.is_active():
time.sleep(0.1)
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
play_audio_callback("output.wav")
如果本文对您有所帮助,请支持下本站哦!!!^_^