5

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicholas
  • 3,517
  • 13
  • 47
  • 86

10 Answers10

21

Just change True to False (I use Python 3.7.1)

import playsound
playsound.playsound('storm.mp3', False)
print ('...')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
15

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()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
void
  • 2,571
  • 2
  • 20
  • 35
4

There is a library in Pygame called mixer and you can add an MP3 file to the folder with the Python script inside and put code like this inside:

from pygame import mixer

mixer.init()
mixer.music.load("mysong.mp3")
mixer.music.play()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rinzler786
  • 109
  • 1
  • 11
  • This is the same as in [the accepted answer](https://stackoverflow.com/questions/44472162/how-can-i-play-audio-playsound-in-the-background-of-a-python-script/44472225#44472225) (but much better explained). – Peter Mortensen Dec 07 '21 at 13:19
3

Well, you could just use pygame.mixer.music.play(x):

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

pygame.mixer.init()
pygame.mixer.music.load('filename.extention')
pygame.mixer.music.play(999)

# Your code here
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wine
  • 31
  • 1
2

You could try just_playback. It's a wrapper I wrote around miniaudio that plays audio in the background while providing playback control functionality like pausing, resuming, seeking and setting the playback volume.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
droptop
  • 1,372
  • 13
  • 24
2

A nice way to do it is to use vlc. Very common and supported library.

pip install python-vlc

Then writing your code

import vlc

#Then instantiate a MediaPlayer object

player = vlc.MediaPlayer("/path/to/song.mp3")

#And then use the play method

player.play()

#You can also use the methods pause() and stop if you need.

player.pause()
player.stop

#And for the super fancy thing you can even use a playlist :)

playlist = ['/path/to/song1.mp3', '/path/to/song2.mp3', '/path/to/song3.mp3']

    for song in playlist:
        player = vlc.MediaPlayer(song)
        player.play()
1
from pygame import mixer

mixer.music.init()
mixer.music.load("audio.mp3") # Paste The audio file location 
mixer.play() 
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Nic3500 Jul 10 '19 at 23:05
  • The code is practically identical to the code in [Rinzler786's answer](https://stackoverflow.com/questions/44472162/how-can-i-play-audio-playsound-in-the-background-of-a-python-script/53906487#53906487) (though the code comment is a slight improvement). And that answer has an explanation. – Peter Mortensen Dec 07 '21 at 13:14
1

Use vlc

import vlc
player = None
def play(sound_file):
    global player
    if player is not None:
        player.stop()
    player = vlc.MediaPlayer("file://" + sound_file)
    player.play()
Ahmad
  • 8,811
  • 11
  • 76
  • 141
  • Can you [expand this answer](https://stackoverflow.com/posts/67877810/edit)? E.g., what is required to be installed? [VLC media player](https://en.wikipedia.org/wiki/VLC_media_player)? Or something else (some development files not part of the VLC media player installation)? Or completely independent of VLC media player itself (some stand-alone libraries)? What platform did you test this on? (But ***without*** "Edit:", "Update:", or similar - the question/answer should appear as if it was written today.) – Peter Mortensen Dec 07 '21 at 13:24
  • [rambopython's answer](https://stackoverflow.com/questions/44472162/how-can-i-play-audio-playsound-in-the-background-of-a-python-script/68877343#68877343) is less terse. – Peter Mortensen Dec 07 '21 at 13:27
1

I used a separate thread to play the sound without blocking the main thread. It works on Ubuntu as well.

from threading import Thread
from playsound import playsound

def play(path):
    """
    Play sound file in a separate thread
    (don't block current thread)
    """
    def play_thread_function:
        playsound(path)

    play_thread = Thread(target=play_thread_function)
    play_thread.start()
bmann
  • 81
  • 6
1

This is a solution to reproduce similar length sounds. This solution worked to me to solve the error:

The specified device is not open or recognized by MCI.

Here follow the syntax as a class method, but you can change it to work even without a class.

Import these packages:

import multiprocessing
import threading
import time

Define this function:

def _reproduce_sound_nb(self, str_, time_s):
        def reproduce_and_kill(str_, time_sec=time_s):
            p = multiprocessing.Process(target=playsound, args=(str_,))
            p.start()
            time.sleep(time_sec)
            p.terminate()
        threading.Thread(target=reproduce_and_kill, args=(str_, time_s), daemon=True).start()
    

In the main program/method:

self._reproduce_sound_nb(sound_path, 3) # path to the sound, seconds after sound stop -> to manage the process end
Gennaro
  • 138
  • 1
  • 2
  • 16