python如何同时录制扬声器和麦克风的声音并输出波形
时间: 2024-03-06 19:47:11 浏览: 108
你可以使用Python中的PyAudio库来同时录制扬声器和麦克风的声音,并使用Matplotlib库来绘制波形。以下是一个简单的示例代码:
```python
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
# 设置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
# 初始化PyAudio
p = pyaudio.PyAudio()
# 打开扬声器输出流
output_stream = p.open(format=FORMAT, channels=CHANNELS,
rate=RATE, output=True)
# 打开音频输入流进行录音
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=0)
print("开始录音......")
fig, ax = plt.subplots()
x = np.arange(0, 2 * CHUNK, 2)
line, = ax.plot(x, np.zeros(CHUNK))
line2, = ax.plot(x, np.zeros(CHUNK))
ax.set_ylim(-32768, 32768)
ax.set_xlim(0, CHUNK)
while True:
data = stream.read(CHUNK)
output_stream.write(data)
data = np.frombuffer(data, dtype=np.int16)
line.set_ydata(data)
data2 = output_stream.read(CHUNK)
data2 = np.frombuffer(data2, dtype=np.int16)
line2.set_ydata(data2)
plt.pause(0.01)
fig.canvas.draw()
# 停止录音
stream.stop_stream()
stream.close()
p.terminate()
print("录音结束!")
```
这段代码会同时录制扬声器和麦克风的声音,并将其实时绘制成波形图。请确保已经安装了PyAudio和Matplotlib库,并且在运行代码之前已经连接好了扬声器和麦克风。你可以按下Ctrl+C来停止录制并关闭窗口。
阅读全文