Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play sound using bytes array

Tags:

python

ffmpeg

How can I play sound using a byte array in Python. To be more precise, I read a byte array from a socket and I want to convert it to sound to understand it. How can I achieve this?

Any libraries would be useful.

like image 487
Dunes Buggy Avatar asked Jun 29 '15 03:06

Dunes Buggy


1 Answers

Try PyAudio which is a binding for PortAudio.

I have used it for creating audio conferences and it worked quite good.

Deep investigations have shown this is the most suitable library for working with raw audio data in real time.

There several examples provided by official docs in Examples section.

As you are going to get data from socket, you will need to bufferize it first. This means, you continually read data from socket and put it to some buffer.

You may need some mechanism for preventing your buffer from growing too much, i.e. use circular buffer or so. But this must be done carefully, because you may face up with sound clipping if sound output device is slow in comparison to speed of incoming data.

After you got some data in your buffer, you will need to play it back. The best way is to tell audio driver to get data when device is ready to consume them. This is done by specifying a callback which will return a chunk of data for device.

So, please, see Play (Callback) example from the official docs.

That example is rather descriptive, but may not answer all of your questions. So, I'll guide you through my code step-by-step:

  1. Create an instance of PyAudio.
  2. Create an audio I/O stream.

Here you can see input=True parameter: you do not need this, as you need to play sound only.

There is another parameter stream_callback which points to on_audio_ready method. This method is called by pyaudio in a separate thread. It pulls data from buffer and returns it to caller. Note: you need to return as much data, as output device is ready to consume (in_data). In my code, if there is less data available, than it is needed, then silence data is appended,

  1. Start your stream by calling its .start_stream() method. I have used Twisted library, so it may look a bit weird for you.
like image 168
oblalex Avatar answered Oct 04 '22 22:10

oblalex