python-使用python获取一段录音

需要安装pyaudio库。

直接上代码:

import pyaudio
import wave

AUDIO_FILE = '录音文件.wav'

def get_audio(filepath, audio_time):          #录音

    CHUNK = 256
    FORMAT = pyaudio.paInt16
    CHANNELS = 1                # 声道数
    RATE = 16000                # 采样率
    RECORD_SECONDS = audio_time
    WAVE_OUTPUT_FILENAME = "录音文件.wav"
    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("*"*10, "开始录音:请在%d秒内输入语音"% (audio_time))
    frames = []
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    print("*"*10, "录音结束\n")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    

if __name__ == '__main__':
    get_audio(AUDIO_FILE,10)

 

posted @ 2018-11-13 21:28  叶念西风  阅读(693)  评论(0编辑  收藏  举报
叶念西风 - 个人博客 & 电脑Run - 维修帮助软件教程安装