cancel
Showing results for 
Search instead for 
Did you mean: 

How do play audio (playsound) in background of Python script?

How do play audio (playsound) in background of Python script?

I am just writing a small python game which I learned from Machine learning online course 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 play sound

def displayIntro():

playsound.playsound('storm.mp3',True)

print('')

print('')

print_slow('The year is 1845, you have just arrived home...')

Also, is there any way of controlling the volume of the play sound module?

I should add that I am using a Mac, and I am not wedded to using play sound, it just seems to be the only module that I can get working.

 

1 REPLY 1

Re: How do play audio (playsound) in background of Python script?

 

Certainly! To play audio in the background while continuing the script execution, you might consider using the threading module in Python. Here's an example of how you could modify your code:

 

import playsound import
threading
def play_audio():
   playsound.playsound('storm.mp3', True)
def displayIntro():
   thread = threading.Thread(target=play_audio)
   thread.start()
print('')
print('')
print_slow('The year is 1845, you have just arrived home...')
# Rest of your code...
# Call your function
displayIntro()

 

By utilizing threading, the play_audio function runs concurrently with the rest of your code, allowing the audio to play in the background while the script continues its execution.

As for controlling the volume using playsound, it doesn't have built-in volume control. You might explore other audio libraries like pygame or pydub that offer more advanced features, including volume adjustment, which could better suit your needs. Experimenting with these libraries might provide more flexibility in controlling audio playback on a Mac environment.

Remember to install the required libraries (pygame or pydub) using pip if you choose to explore alternatives to playsound.