Python: real-time streaming audio with PyAudio (or something else)?

I am currently using NumPy to create a WAV file from a NumPy array. I wonder if it is possible to play the NumPy array in real time before it is written to the hard drive. All the examples that I found using PyAudio initially rely on writing the NumPy array to a WAV file, but I would like to have a preview function that simply splashes the NumPy array onto the audio output.

Must also be cross-platform. I am using Python 3 (Anaconda distribution).

+5
source share
3 answers

It worked! Thanks for the 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!") 

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

+4
source

It is really simple with python-sounddevice :

 import sounddevice as sd sd.play(myarray, 44100) 
+2
source

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

There is no need to write a WAV file first, you need a data stream in the desired format.

I am adding the example below if the link ever goes out (note that I did not 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() 
+1
source

All Articles