Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 hard drive. All examples I found using PyAudio rely on writing the NumPy array to a WAV file first, but I'd like to have a preview function that just spits out the NumPy array to the audio output.

Should be cross-platform, too. I'm using Python 3 (Anaconda distribution).

like image 413
Mario Krušelj Avatar asked Jul 28 '15 11:07

Mario Krušelj


People also ask

What is Pyaudio stream?

Stream to play or record audio. Play audio by writing audio data to the stream using pyaudio.Stream.write() , or read audio data from the stream using pyaudio.Stream.read() . (


2 Answers

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.

like image 135
Mario Krušelj Avatar answered Oct 16 '22 06:10

Mario Krušelj


This is really simple with python-sounddevice:

import sounddevice as sd
sd.play(myarray, 44100)
like image 21
Matthias Avatar answered Oct 16 '22 07:10

Matthias