35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
"""
|
||
本地录音,保存为wav格式,存储在data/speaker_wav目录下
|
||
"""
|
||
import pyaudio
|
||
import wave
|
||
|
||
def record_audio(filename, duration=5, format=pyaudio.paInt16, channels=1, rate=16000):
|
||
"""
|
||
本地录音,保存为wav格式,存储在data/speaker_wav目录下
|
||
"""
|
||
p = pyaudio.PyAudio()
|
||
stream = p.open(format=format, channels=channels, rate=rate, input=True, frames_per_buffer=1024)
|
||
|
||
print("按下回车键开始录音...")
|
||
input()
|
||
frames = []
|
||
for i in range(0, int(rate / 1024 * duration)):
|
||
data = stream.read(1024)
|
||
frames.append(data)
|
||
print("录音结束")
|
||
stream.stop_stream()
|
||
stream.close()
|
||
p.terminate()
|
||
wav_file = wave.open(filename, 'wb')
|
||
wav_file.setnchannels(channels)
|
||
wav_file.setsampwidth(p.get_sample_size(format))
|
||
wav_file.setframerate(rate)
|
||
wav_file.writeframes(b''.join(frames))
|
||
wav_file.close()
|
||
|
||
if __name__ == "__main__":
|
||
record_audio(
|
||
"data/speaker_wav/test.wav",
|
||
duration=5
|
||
) |