pythonaudiopython-playsound

How can I play audio (playsound) in the background of a Python script?


I am just writing a small Python game for fun and I have a function that does the beginning narrative.

I am trying to get the audio to play in the background, but unfortunately the MP3 file plays first before the function continues.

How do I get it to run in the background?

import playsound

def displayIntro():
    playsound.playsound('storm.mp3',True)
    print('')
    print('')
    print_slow('The year is 1845, you have just arrived home...')

Also, is there a way of controlling the volume of the playsound module?

I am using a Mac, and I am not wedded to using playsound. It just seems to be the only module that I can get working.


Solution

  • In Windows:

    Use winsound.SND_ASYNC to play them asynchronously:

    import winsound
    winsound.PlaySound("filename", winsound.SND_ASYNC | winsound.SND_ALIAS )
    

    To stop playing

    winsound.PlaySound(None, winsound.SND_ASYNC)
    

    On Mac or other platforms:

    You can try this Pygame/SDL

    pygame.mixer.init()
    pygame.mixer.music.load("file.mp3")
    pygame.mixer.music.play()