Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

howto stream numpy array into pyaudio stream?

I'm writing a code that supposed to give some audio output to the user based on his action, and I want to generate the sound rather than having a fixed number of wav files to play. Now, what I'm doing is to generate the signal in numpy format, store the data in a wav file and then read the same file into pyaudio. I think this is redundant, however, I couldn't find a way to do that. My question is, can I stream a numpy array (or a regular list) directly into my the pyaudio to play?

like image 638
Yotam Avatar asked Jan 09 '23 05:01

Yotam


1 Answers

If its just playback and does not need to be synchronised to anything then you can just do the following:

# Open stream with correct settings
stream = self.p.open(format=pyaudio.paFloat32,
                         channels=CHANNELS,
                         rate=48000,
                         output=True,
                         output_device_index=1
                         )
# Assuming you have a numpy array called samples
data = samples.astype(np.float32).tostring()
stream.write(data)

I use this method and it works fine for me. If you need to record at the same time then this won't work.

like image 65
Maximillion Avatar answered Jan 13 '23 17:01

Maximillion