美文网首页
pydudio&wave

pydudio&wave

作者: 一盏省油的小灯 | 来源:发表于2018-05-25 18:21 被阅读20次

wave库官方文档说明

pyaudio库说明文档

以下是一个录音的例子:
import pyaudio
import wave
import logging

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000

class AudioMic(object):

    """docstring for AudioMic"""

    def __init__(self):
        super(AudioMic, self).__init__()

        logging.basicConfig(
                    level=logging.INFO,
                    filename='mic.log',
                    filemode ='w',
                    format='%(asctime)s-%(levelname)s:%(message)s')
        self.frames = []

        self.audio = pyaudio.PyAudio()
        self.stream = self.audio.open(format=FORMAT,
                                    channels=CHANNELS,
                                    rate=RATE,
                                    input=True,
                                    frames_per_buffer=CHUNK)

        logging.info(u"created a recording stream:\n\trate="+str(RATE)+" format="+str(FORMAT)+" channels="+str(CHANNELS)+"\n")

    def startRecord(self,time=50):
        logging.info("record starting!\n")
        for i in range(0, int(RATE / CHUNK * time)):
            # data = stream.read(CHUNK)
            self.frames.append(self.stream.read(CHUNK))

    def stopRecord(self):
        logging.info("record over\n")
        self.stream.stop_stream()
        self.stream.close()
        self.audio.terminate()

        self.savefile()

    def savefile(self,filename='output.wav'):
        wf = wave.open(filename, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(self.audio.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(self.frames))
        wf.close()
        
        self.frames = []

if __name__ == '__main__':
    mic = AudioMic()
    mic.startRecord(3)
    mic.stopRecord()

相关文章

网友评论

      本文标题:pydudio&wave

      本文链接:https://www.haomeiwen.com/subject/cwmujftx.html