Search code examples
pythonpython-3.xpython-sounddevice

Play a sound asynchronously in a while loop


How can I play a sound asynchronously in a while loop, but don't overlap the sound. Wait for the previous play to finish and only then play it again and so on, until the while loop is running. And of course, the while loop should continue to run while the play is running.

import time
from playsound import playsound

while True:
    time.sleep(0.1)
    playsound('sound.wav', block=False)  # Please suggest another module, "playsound" stopped working and I gave up on fixing it.
    print('proof that the while loop is running while the sound is playing')

edit: One more thing, the play should not queue up, once the while loop stops, play must stop as well (only let the one playing play out)


Solution

  • I managed to solve this the next day.

    I used threading and i had to use it in a class to check if it's alive because I couldn't just t1 = threading.Thread(target=func) t1.start() in the while loop because i needed to check if the thread is alive before.

    So...

    import threading
    
    from playsound import playsound
    
    
    class MyClass(object):
        def __init__(self):
            self.t1 = threading.Thread(target=play_my_sound)
    
    
    def play_my_sound():
        playsound('sound.wav')
    
    
    def loop():
        while True:
            if not my_class.t1.is_alive():
                my_class.t1 = threading.Thread(target=play_my_sound)
                my_class.t1.start()
    
    
    if __name__ == "__main__":
        my_class = MyClass()
        loop()
    

    This answers my question, the sound plays on it's own thread in the while loop and it only starts playing if the previous one has finished.

    Note: i had issues with the playsound library, but it was because i had to use \\ for the path instead of / - in my original code the sounds are not in the same folder as the main script. I also had to downgrade to playsound==1.2.2 version.