简体   繁体   English

如何使用pygame在python中播放音乐?

[英]How to play music in python using pygame?

import pygame
pygame.mixer.init()
pygame.mixer.music.load(file)#any mp3 file
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
  pygame.time.Clock().tick()

I know this is the code to play the music in python with pygame Can you explain why we use 我知道这是使用pygame在python中播放音乐的代码, 您能解释一下为什么我们使用

while pygame.mixer.music.get_busy():
   pygame.time.Clock().tick()

Basically, the play() function is asynchronous .It means it won't wait for a return message to continue. 基本上, play()函数是异步的 ,这意味着它不会等待返回消息继续。 And when the program execution reaches the end, mixer object will be destroyed and the music will stop. 当程序执行结束时,混音器对象将被破坏,音乐将停止。 To avoid that we use 为了避免这种情况,我们使用

while pygame.mixer.music.get_busy():
   pygame.time.Clock().tick()

to run the while loop until the music finishes. 运行while循环直到音乐结束。 Then the mixer object will not be destroyed until the music playing finishes. 这样,直到音乐播放完成,混音器对象才会被破坏。 get_busy() method is used to check if the music stream is playing. get_busy()方法用于检查音乐流是否正在播放。

from pygame import*
mixer.init()
mixer.music.load('music filename or path with extension .mp3')
mixer.music.play()

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

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