spatialaudio / python-sounddevice

:sound: Play and Record Sound with Python :snake:
https://python-sounddevice.readthedocs.io/
MIT License
980 stars 145 forks source link

Decode on the fly #501

Closed sagalpreet closed 4 months ago

sagalpreet commented 7 months ago

Hi, for my use-case, I want to be able to play from an audio file (wav/mp3/flac/ogg), the constraint being that the file is continuously being written to by another process. I want my program to start playing the audio as soon as possible.

The closest example I could find was playing very long sound file without using numpy but that doesn't seem to work for me.

Essentially, instead of decoding the entire file all at once, I would like to decode it on the fly, so that whatever data (which is playable) is already there in the file, I can play it and wait for more to be written before proceeding.

Is this possible to achieve using python-sounddevice?

mgeier commented 7 months ago

You can use the sounddevice module to play the audio data, but getting the data from somewhere else is out of scope.

I don't think it's a good idea to write and read the same file from two different processes, it sounds dangerous, but this might be platform-dependent. It's probably safer to transport the data via a named pipe or a socket or something.

You can look at the play_stream.py example, which does decode a web stream on the fly, but that's done with ffmpeg. The sounddevice module then only plays the decoded chunks.

play from an audio file (wav/mp3/flac/ogg), the constraint being that the file is continuously being written to

Apart from the access via multiple processes at the same time, another problem is that all the formats you mentioned expect the length of the file to be stored in the header, which is of course not known when the audio data is still being written.

sagalpreet commented 7 months ago

Thanks @mgeier for the response. I tried using ffmpeg but seems like it is not able to handle the case of reading from a file that is being written to in parallel. Anyways, that is more of an ffmpeg issue, so I have raised it there, ffmpeg-python/issues/803.