python 开发IEnglish (二) 录音

下载pyaudio

pip install pyaudio

如果不行请见这里

创建recording.py

import pyaudio
import wave

class recording:
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 8000

def record(save_path, seconds=14):
    p = pyaudio.PyAudio()
    stream = p.open(
        format=recording.FORMAT,
        channels=recording.CHANNELS,
        rate=recording.RATE,
        input=True,
        frames_per_buffer=recording.CHUNK
    )
    
    frames = []
    for n in range(0, int(recording.RATE / recording.CHUNK * seconds)):
        data = stream.read(recording.CHUNK)
        frames.append(data)
        
    stream.stop_stream()
    stream.close()
    p.terminate()
    
    wf = wave.open(save_path, 'wb')
    wf.setnchannels(recording.CHANNELS)
    wf.setsampwidth(p.get_sample_size(recording.FORMAT))
    wf.setframerate(recording.RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

你可能感兴趣的:(python,开发IEnglish,python,python,stream,wave)