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

Posted on

Question :

How do play audio (playsound) in background of 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():
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 playsound, it just seems to be the only module that I can get working.

Asked By: ScoutEU


Answer #1:

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)

In mac or other platforms:
You can try this Pygame/SDL

Answered By: void

Answer #2:

Just change True to False (I use python 3.7.1)

import playsound
playsound.playsound('storm.mp3', False)
print ('...')
Answered By: ??????? ?????????

Answer #3:

Well you could just use

#!/usr/bin/env python3
# Any problems contact me on instagram @vulnerabilties
import pygame

Answered By: Wine

Answer #4:

There is a library In pygame called mixer and you can add a mp3 file to the folder with the python script inside and put code like this inside:

from pygame import mixer

I hope you found my answer helpful

Answered By: Rinzler786

Answer #5:

from pygame import mixer"audio.mp3") # Paste The audio file location 
Answered By: Abhrajeet Sarder

Answer #6:

Playsound has an option for running in the background -> additional argument to be set to 0:

playsound("xxxxx.mp3", 0)
Answered By: oscar

Leave a Reply

Your email address will not be published. Required fields are marked *