Nicholas
Nicholas

Reputation: 3737

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.

Upvotes: 6

Views: 49372

Answers (10)

bmann
bmann

Reputation: 91

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()

Upvotes: 1

droptop
droptop

Reputation: 1681

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.

Upvotes: 3

Just change True to False (I use Python 3.7.1)

import playsound
playsound.playsound('storm.mp3', False)
print ('...')

Upvotes: 22

Rinzler786
Rinzler786

Reputation: 109

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()

Upvotes: 4

Wine
Wine

Reputation: 31

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

Upvotes: 3

void
void

Reputation: 2652

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()

Upvotes: 17

Gennaro
Gennaro

Reputation: 138

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

Upvotes: 1

rambopython
rambopython

Reputation: 21

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()

Upvotes: 2

Ahmad
Ahmad

Reputation: 9708

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()

Upvotes: 0

user10762774
user10762774

Reputation:

from pygame import mixer

mixer.music.init()
mixer.music.load("audio.mp3") # Paste The audio file location 
mixer.play() 

Upvotes: 1

Related Questions