下面我将为你详细讲解“python实现录音小程序”的完整攻略,过程中包含以下几个步骤:
- 安装PyAudio和wave库
- 录音
- 保存录音文件
- 示例说明
1. 安装PyAudio和wave库
要实现录音功能,我们需要使用到PyAudio和wave库。在终端中输入以下命令来安装:
pip install pyaudio wave
2. 录音
在Python中实现录音,需要用到PyAudio库。以下是录音代码范例:
import pyaudio
# 配置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 5
p = pyaudio.PyAudio()
# 开始录音
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
3. 保存录音文件
录取完声音之后,我们需要将录音保存成文件格式,常用的是wav格式。示例代码如下:
import wave
wf = wave.open("output.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
以上就是实现Python录音小程序的完整攻略。下面给出两个具体示例:
- 录制5秒钟的音频并保存为wav格式文件
import pyaudio
import wave
# 配置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 5
p = pyaudio.PyAudio()
# 配置录音文件输出
wf = wave.open("output.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
# 开始录音
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
wf.writeframes(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
- 录制15秒钟的音频并保存为wav格式文件
import pyaudio
import wave
# 配置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 15
p = pyaudio.PyAudio()
# 配置录音文件输出
wf = wave.open("output.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
# 开始录音
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
wf.writeframes(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf.close()
以上两个示例可以在一些需要录制音频的应用场景中使用,如语音识别、语音合成、声音转文字等等。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python实现录音小程序 - Python技术站