pythonpython-sounddevice

Playing recorded audio in a python file not working


I'm using sounddevice to record and play audio with python. I'm using a very simple code which is running well from the python interpreter:

import sounddevice as sd
from time import sleep

fs = 44100
myrec = sd.rec(int(fs*3), samplerate=fs, channels=2)
sleep(3)
sd.play(myrec, fs)

However, when I'm trying to run this code from a python file (or using PyCharm) it just won't play. What is wrong with the code that's making it happen?


Solution

  • The problem is that sounddevice plays audio in background. When the script ends, it won't wait for the playback to complete. In Python interpreter, you stay in the session to listen, but from a script you need to wait for it explicitly:

    import sounddevice as sd
    from time import sleep
    
    fs = 44100
    myrec = sd.rec(int(fs*3), samplerate=fs, channels=2)
    sd.wait()
    sd.play(myrec, fs)
    sd.wait()