How can audio recording functionality be implemented in…
To enable audio recording functionality, you can utilize the audio processing library pyaudio in Python.
Firstly, you need to install the pyaudio library, which can be done by using the following command:
pip install pyaudio
Next, you can use the following code to implement audio recording function:
import pyaudio
import wave
# 设置参数
chunk = 1024 # 每次录制的音频大小
format = pyaudio.paInt16 # 音频格式
channels = 2 # 声道数
rate = 44100 # 采样率
record_seconds = 5 # 录制时长
output_file = "output.wav" # 输出文件名
# 创建PyAudio对象
p = pyaudio.PyAudio()
# 打开音频流
stream = p.open(format=format,
channels=channels,
rate=rate,
input=True,
frames_per_buffer=chunk)
print("开始录制音频...")
frames = []
# 录制音频
for i in range(int(rate / chunk * record_seconds)):
data = stream.read(chunk)
frames.append(data)
print("录制音频结束.")
# 关闭音频流
stream.stop_stream()
stream.close()
p.terminate()
# 保存音频到文件
wf = wave.open(output_file, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(format))
wf.setframerate(rate)
wf.writeframes(b''.join(frames))
wf.close()
print("音频保存成功:", output_file)
In the code above, the parameters for recording audio such as audio size, format, number of channels, sampling rate, and duration were set first. Next, a PyAudio object was created and the audio stream was opened using the open() method. Then, audio data was continuously read from the stream in a loop and added to the frames list to complete the audio recording. Finally, the audio stream was closed, the PyAudio object terminated, and the recorded audio data was saved to a file.
After running the above code, audio recording will begin, and once completed, it will be saved to the specified file. Parameters and file names can be modified based on actual needs.