简体   繁体   中英

How do I repeat music using pygame.mixer?

I have created the following code that plays mp3 music using pygame.mixer. However, the music does not repeat. Any idea's on how I would make it so that the music does repeat? Here is the code:

playlist = list()
playlist.append ( "put music here.mp3" )
playlist.append ( "put music here.mp3" )

pygame.mixer.music.load ( playlist.pop() )  
pygame.mixer.music.queue ( playlist.pop() )
pygame.mixer.music.set_endevent ( pygame.USEREVENT )  
pygame.mixer.music.play()           

a = 0

running = True
while a == 0:
   while running:
      for event in pygame.event.get():
         if event.type == pygame.USEREVENT:    
            if len ( playlist ) >1:       
               pygame.mixer.music.queue ( playlist.pop() )`

根据pygame文档,您可以为pygame.mixer.music.play()传入-1以无限期地重复播放音乐。

pygame.mixer.music.play(loops=-1)

gave me error:

pygame.mixer.music.play(loops=-1)
TypeError: play() takes no keyword arguments

What did work is passing just the number:

pygame.mixer.music.play(-1)

Hope it helps someone!

To play a music X times use, pygame.mixer.music.play(X) , ie:

import pygame
pygame.init()
pygame.display.set_mode(pygame.display.list_modes()[-1]) # smallest resolution available
pygame.mixer.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play(5) # repeat 5 times
pygame.mixer.music.queue("test2.wav")   # queue test2.wav after test.wav plays 5 times
clock = pygame.time.Clock()
clock.tick(10)
while pygame.mixer.music.get_busy():
    pygame.event.poll()
    clock.tick(10)

PS:

  • I was able to play music with pygame only after creating a display .

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