[Python] How to play music sequentially in Python without blocking program execution?

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm developing a Python application that needs to play music tracks sequentially. Currently, I'm using pygame.mixer to play the audio like this:

    from pygame import mixer
    from time import sleep

    mixer.init()
    mixer.music.load(self.current_song)
    mixer.music.play()
    sleep(float(music_length))


    This approach works for playing the audio, but I have to use sleep() to wait for the song to finish. Otherwise, the program continues execution, and multiple songs may be played over each other. However, using sleep() blocks the entire program, preventing any interaction (e.g., pausing or stopping the music mid-play).

    Previously, I used an external command-line tool like this:

    import subprocess

    subprocess.run(["play", self.current_song])


    This worked well because it naturally blocked until the audio finished playing, but I want to avoid external dependencies and stick to a pure Python solution for easier distribution.

    Question: Is there a way to play audio in Python using a library like pygame (or another pure Python alternative) that allows waiting for a track to finish without blocking the entire program? Ideally, I’d like to retain the ability to interact with the program during playback (e.g., add pause/resume functionality) and ensure songs don’t overlap.

    Any suggestions for a better approach or library would be appreciated.

    Continue reading...

Compartilhe esta Página