Python: realtime audio streaming with PyAudio (or something else)?

前端 未结 3 1848
耶瑟儿~
耶瑟儿~ 2020-12-24 03:21

Currently I\'m using NumPy to generate the WAV file from a NumPy array. I wonder if it\'s possible to play the NumPy array in realtime before it\'s actually written to the h

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 04:01

    This has worked! Thanks for help!

    def generate_sample(self, ob, preview):
        print("* Generating sample...")
        tone_out = array(ob, dtype=int16)
    
        if preview:
            print("* Previewing audio file...")
    
            bytestream = tone_out.tobytes()
            pya = pyaudio.PyAudio()
            stream = pya.open(format=pya.get_format_from_width(width=2), channels=1, rate=OUTPUT_SAMPLE_RATE, output=True)
            stream.write(bytestream)
            stream.stop_stream()
            stream.close()
    
            pya.terminate()
            print("* Preview completed!")
        else:
            write('sound.wav', SAMPLE_RATE, tone_out)
            print("* Wrote audio file!")
    

    Seems so simple now, but when you don't know Python very well, it seems like hell.

提交回复
热议问题