使用Python编写实现简单的音频录制和播放程序
发布时间:2024-01-09 07:06:38
音频录制和播放是常见的音频处理任务之一。Python提供了多个库来实现音频录制和播放功能,其中最常用的是pyaudio库。下面是一个使用Python编写的实现简单音频录制和播放程序的示例:
首先,需要安装pyaudio库。可以使用以下命令在命令行中安装:
pip install pyaudio
接下来,我们将编写一个名为audio_recorder_player.py的Python脚本。以下是完整的脚本:
import pyaudio
import wave
def record_audio(file_name, duration):
chunk = 1024
sample_format = pyaudio.paInt16
channels = 2
sample_rate = 44100
p = pyaudio.PyAudio()
stream = p.open(format=sample_format,
channels=channels,
rate=sample_rate,
frames_per_buffer=chunk,
input=True)
frames = []
print("Recording audio...")
for i in range(0, int(sample_rate / chunk * duration)):
data = stream.read(chunk)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wave_file = wave.open(file_name, 'wb')
wave_file.setnchannels(channels)
wave_file.setsampwidth(p.get_sample_size(sample_format))
wave_file.setframerate(sample_rate)
wave_file.writeframes(b''.join(frames))
wave_file.close()
print("Audio recorded and saved as", file_name)
def play_audio(file_name):
chunk = 1024
wave_file = wave.open(file_name, 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wave_file.getsampwidth()),
channels=wave_file.getnchannels(),
rate=wave_file.getframerate(),
output=True)
print("Playing audio...")
data = wave_file.readframes(chunk)
while data:
stream.write(data)
data = wave_file.readframes(chunk)
stream.stop_stream()
stream.close()
p.terminate()
print("Audio playback completed")
# 使用示例
record_audio("recorded_audio.wav", 5) # 录制音频并保存为recorded_audio.wav
play_audio("recorded_audio.wav") # 播放recorded_audio.wav
上面的示例代码首先定义了两个函数:record_audio()和play_audio()。record_audio()函数用于录制音频,它接收两个参数:文件名和录制时长。play_audio()函数用于播放音频,它接收一个参数:文件名。
在使用示例部分,我们调用record_audio()函数录制5秒钟的音频并将其保存为recorded_audio.wav文件。之后,我们调用play_audio()函数播放recorded_audio.wav文件。
以上就是一个简单的音频录制和播放程序的实现示例。你可以根据自己的需要进行修改和扩展。
