python系列&deep_study系列:pyaudio 音频录制区分声道设备 demo
pyaudio 音频录制区分声道设备 demo
pyaudio 音频录制区分声道设备 demo
常用采集率RATE = 16000
import pyaudio
import wave
# 参数设置
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
# 创建 PyAudio 对象
p = pyaudio.PyAudio()
# 麦克风录制
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("Start recording from microphone...")
frames_mic = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames_mic.append(data)
print("Recording from microphone completed.")
# 停止录音
stream.stop_stream()
stream.close()
# 杨声器录制
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input_device_index=1, # 设置为杨声器的输入设备索引
input=True,
frames_per_buffer=CHUNK)
print("Start recording from yang speaker...")
frames_yang = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames_yang.append(data)
print("Recording from yang speaker completed.")
# 停止录音
stream.stop_stream()
stream.close()
# 关闭 PyAudio 对象
p.terminate()
# 保存录音文件
wf = wave.open("1.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames_mic))
wf.close()
wf = wave.open("2.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames_yang))
wf.close()