Archive

Posts Tagged ‘in memory’

Play a sound file from memory

February 6, 2024 Leave a comment

Problem

I wanted to play short sound files a lot of times. Calling an external program each time to play a file would have been too slow. How to read sound files in the memory and play them from there?

Solution

First I tried the package simpleaudio. It worked well but it turned out that it couldn’t play every .wav file. VLC could play my file correctly, but simpleaudio just produced some noise. So I needed another solution.

And that’s how I found soundfile and sounddevice. Their usage is very simple:

import soundfile as sf
import sounddevice as sd

samples, samplerate = sf.read('file.wav')
sd.play(samples, samplerate)
sd.wait()

To use them, you also need to install numpy.

More info here: https://stackoverflow.com/a/42387773/232485

Update:

I had some .wav files that were not played correctly with soundfile+sounddevice. So I ended by using soundfile+sounddevice for certain files and by using simpleaudio for some other files.

Links

Categories: python Tags: , , ,