使用Python实现录音和波形实时显示

本文展示了如何使用Python的pyaudio库从麦克风实时捕捉音频数据,并通过matplotlib进行波形显示,同时将音频保存为WAV文件。代码演示了音频输入流处理和图形界面更新的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码由ChatGPT 3.5 生成

import pyaudio
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import wave

# Constants for audio input
FORMAT = pyaudio.paInt16
CHANNELS = 1  # Mono audio
RATE = 44100  # Sample rate (samples per second)
CHUNK = 4096  # Number of frames per buffer
WAVE_OUTPUT_FILENAME = 'audio_output.wav'

# Initialize PyAudio
audio = pyaudio.PyAudio()

# Open a stream to capture audio from the microphone
stream = audio.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

# Initialize the plot for real-time waveform display
plt.ion()  # Turn on interactive mode for real-time updating
fig, ax = plt.subplots()
x = np.arange(0, CHUNK)
line, = ax.plot(x, np.zeros(CHUNK))

ax.set_xlim(0, CHUNK)
ax.set_ylim(-32768, 32767)  # Assuming 16-bit audio

# Create a wave file to save the audio
wave_output_file = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wave_output_file.setnchannels(CHANNELS)
wave_output_file.setsampwidth(audio.get_sample_size(FORMAT))
wave_output_file.setframerate(RATE)


# Function to update the plot with the latest audio data
def update_plot(data):
    line.set_ydata(data)
    fig.canvas.draw()
    fig.canvas.flush_events()


# Function to continuously capture and display audio
def display_audio_waveform():
    while True:
        try:
            audio_data = np.frombuffer(stream.read(CHUNK), dtype=np.int16)
            update_plot(audio_data)
            wave_output_file.writeframes(audio_data)
        except KeyboardInterrupt:
            break


# Start displaying the audio waveform
display_audio_waveform()

# Close the audio stream and terminate PyAudio
stream.stop_stream()
stream.close()
audio.terminate()

# Close the wave file
wave_output_file.close()
print('Audio saved to', WAVE_OUTPUT_FILENAME)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值