1
 import pygame

 pygame.mixer.init()

 pygame.mixer.music.load("myFile.Mp3")

 pygame.mixer.music.play(-1) # note -1 for playing in loops

 # do whatever

 # when ready to stop do:

 pygame.mixer.pause()

 If you want to unpause:

 pygame.mixer.unpause()

I have a question about pygame! I have the same pygame setting as above my question: When I click the main python code How can I keep this constantly playing in the background instead of stopping when I start Main.py?

I tried the code above but: it It starts when I boot up the Raspberry pi 4B but Stops playing when I click Main.py.

Mark Liles
  • 11
  • 2

1 Answers1

0

Personally, I’d recommend you use the playsound module, as it implements this pretty easily. Run pip install playsound, then you can include this in your code:

playsound("sound_file.mp3", block=False)

Alternatively, you could make a separate thread to play the song using the builtin threading module. I believe it would look like this:

import threading
import pygame

pygame.mixer.init()

def play_song():
     pygame.mixer.music.load("my_song.mp3")

threading.Thread(target=play_song).start()

I’d personally recommend the first one, however. If you want to play the song constantly in a loop, you could do something like this, with a combination of the two:

def play_song():
    while True:
        playsound("my_song.mp3", block=True)


song_thread = threading.Thread(target=play_song, name='Background_song')
song_thread.daemon = True  # Stops the song when the main file is closed
song_thread.start()
Anonymous
  • 452
  • 2
  • 9