How to play an audiofile with pyaudio?

前端 未结 2 594
故里飘歌
故里飘歌 2020-12-17 01:16

I do not understand the example material for pyaudio. It seems they had written an entire small program and it threw me off.

How do I just play a single audio file?

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 01:33

    May be this small wrapper (warning: created on knees) of their example will help you to understand the meaning of code they wrote.

    import pyaudio
    import wave
    import sys
    
    class AudioFile:
        chunk = 1024
    
        def __init__(self, file):
            """ Init audio stream """ 
            self.wf = wave.open(file, 'rb')
            self.p = pyaudio.PyAudio()
            self.stream = self.p.open(
                format = self.p.get_format_from_width(self.wf.getsampwidth()),
                channels = self.wf.getnchannels(),
                rate = self.wf.getframerate(),
                output = True
            )
    
        def play(self):
            """ Play entire file """
            data = self.wf.readframes(self.chunk)
            while data != '':
                self.stream.write(data)
                data = self.wf.readframes(self.chunk)
    
        def close(self):
            """ Graceful shutdown """ 
            self.stream.close()
            self.p.terminate()
    
    # Usage example for pyaudio
    a = AudioFile("1.wav")
    a.play()
    a.close()
    

提交回复
热议问题