user9575308
user9575308

Reputation:

How can I play an mp3 as a background process with Python3?

I'm trying to play an mp3 as a background process, but I'm not being able to do it. Is it even possible?

import pygame
from daemonize import Daemonize
from time import sleep

pid = '/tmp/mpee3.pid'
def startSong():
    pygame.mixer.init()
    pygame.mixer.music.load('test.mp3')
    pygame.mixer.music.play(0)

def main():
    while pygame.mixer.music.get_busy():
        sleep(0.1)

if __name__ == '__main__':
    startSong()
    daemon = Daemonize(app='mpee3', pid=pid, action=main)
    daemon.start()

I'm not getting error messages, but the song doesn't play. If I do in the end

if __name__ == '__main__':
    startSong()
    main()

The song plays, but if I try to use daemonize, it doesn't play.

Upvotes: 0

Views: 69

Answers (1)

Rotartsi
Rotartsi

Reputation: 567

You need to call pygame.init() to initialize everything else. Also, use pygame.mixer.play(-1) to loop the song indefinitely.

I don't know Daemonize, but based on the name, it probably spawns a detached thread. You're immediately exiting the main thread, forcing your song to stop. Try adding while 1: pass after daemon.start()

Try:

import pygame

pygame.init()

from daemonize import Daemonize
from time import sleep

pid = '/tmp/mpee3.pid'
def startSong():
    pygame.mixer.init()
    pygame.mixer.music.load('test.mp3')
    pygame.mixer.music.play(-1)

def main():
    while pygame.mixer.music.get_busy():
        sleep(0.1)

if __name__ == '__main__':
    startSong()
    daemon = Daemonize(app='mpee3', pid=pid, action=main)
    daemon.start()
    while 1:
        pass

Upvotes: 2

Related Questions