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

前端 未结 3 1846
耶瑟儿~
耶瑟儿~ 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:15

    As you can see in the examples, pyaudio just reads data from the WAV file and writes that to the stream.

    It is not necessary to write a WAV file first, you just need a stream of data in the right format.

    I'm adding the example below in case the link ever goes dead (note that I didn't write this code):

    """PyAudio Example: Play a WAVE file."""
    
    import pyaudio
    import wave
    import sys
    
    CHUNK = 1024
    
    if len(sys.argv) < 2:
        print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
        sys.exit(-1)
    
    wf = wave.open(sys.argv[1], 'rb')
    
    p = pyaudio.PyAudio()
    
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    
    data = wf.readframes(CHUNK)
    
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    
    stream.stop_stream()
    stream.close()
    
    p.terminate()
    

提交回复
热议问题