Search code examples
pythonaudiopydub

play audio file in the background


I want to play an audio file in the background (without blocking the rest of my code) using Pydub library. Here is the code I have so far but it will wait till the audio finishes and then run the remaining of the code

sound = AudioSegment.from_wav('myfile.wav')
play(sound)
print("I like this line to be executed simoultinously with the audio playing")

Solution

  • Play your sound in a new thread:

    from pydub import AudioSegment
    from pydub.playback import play
    import threading
    
    sound = AudioSegment.from_wav('myfile.wav')
    t = threading.Thread(target=play, args=(sound,))
    t.start()
    
    print("I like this line to be executed simoultinously with the audio playing")