1
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

while pygame.mixer.music.get_busy():
   pygame.time.Clock().tick()
Akshaj Dev
  • 11
  • 5
  • Basically, *you don't have to call the `Clock.tick()` function (in this case)*; in fact I haven't seen someone create a `pygame.Clock` object on every `tick()` call. To justify any possible uses of the `tick()` method, I believe that more context is needed. – Jerrybibo Jul 19 '18 at 15:46
  • Possible duplicate of [How can I play an mp3 with pygame?](https://stackoverflow.com/questions/7746263/how-can-i-play-an-mp3-with-pygame) – skrx Jul 19 '18 at 18:04

2 Answers2

0

Basically, the play() function is asynchronous.It means it won't wait for a return message to continue. 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. 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.

Nipun Thennakoon
  • 3,586
  • 1
  • 18
  • 26
0
from pygame import*
mixer.init()
mixer.music.load('music filename or path with extension .mp3')
mixer.music.play()
riishiiraz
  • 31
  • 2