简体   繁体   English

为何pygame在退出前需要time.sleep播放声音?

[英]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 我只是玩Python播放MP3文件并碰到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 我可以用它来播放音乐,但是以某种方式我需要添加time.sleep(SECONDS)以便播放音乐,否则当我在终端机中运行时它会立即存在

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 我并没有尝试创建游戏或任何东西,正如我提到的那样,我只是在玩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. 要说“为什么” pygame.mixer.music并不是真正被设计为前台进程:的想法是,这是背景音乐在其他运行时播放。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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