简体   繁体   中英

Why does pygame need time.sleep in to play sound before exiting?

I am just playing around with Python playing MP3 files and bumped into pygame

I got it to play the music but somehow I need to add time.sleep(SECONDS) in order for the music to play or else it'll just exist right away when I run in terminal

Is there a reason for this or I am not doing it right?

import pygame, time
from pygame.locals import *

pygame.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
pygame.mixer.music.load("path/to/mp3/file")
pygame.mixer.music.play()
time.sleep(32)

I am not trying to create a game or anything, as I mentioned I am just playing around with Python

To speak to the "why" -- pygame.mixer.music isn't really designed to be a foreground process: the idea is that this is background music to play while something else runs. If the user says they want to exit a game, they'll usually be annoyed if that game keeps running until the current background-music track is finished.


If you want to block until the music is finished, one inefficient-but-easy way to do that is with a loop that checks for completion:

while pygame.mixer.music.get_busy():
  time.sleep(0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM