2017-08-09 51 views
2

我使用隊列功能試過,但如何安排的音頻文件中的第一個歌曲結束後在pygame的自動播放?

pygame.mixer.music.queue(filename) 

似乎並不奏效。

下面是我用它來運行我的mp3文件中的代碼:

def playmusic(self): 
    pygame.mixer.init() 
    pygame.mixer.music.load(self.music_link+self.files[self.file_index]) 
    pygame.mixer.music.play() 
    self.pausedmusic = 0 
    self.file_index = self.fileindex + 1 

    pygame.mixer.music.queue(self.music_link+self.files[self.file_index]) 

我試圖用事件,但沒有得到來自它的解決辦法。

如果我使用此代碼,

while(pygame.mixer.music.get_busy()): 
    continue 
self.playmusic() 

的Tkinter的GUI沒有響應,但歌曲不斷玩,它會自動播放下一首歌曲,也讓我的球員沒有反應,直到所有歌曲。

我使用Python 3.6。

回答

1

把你的音樂文件(路徑)到一個列表,自定義一個userevent並調用pygame.mixer.music.set_endevent(YOUR_USEREVENT)。然後將Pygame的歌曲時完成了這個事件添加到事件隊列,你可以執行一些代碼來改變當前歌曲的指數。在下面的例子中,你可以通過按右箭頭鍵增加索引或者等待一首歌結束(在SONG_FINISHED事件發出),並計劃將選擇一個隨機播放歌曲(指數)。

import random 
import pygame as pg 


pg.mixer.pre_init(44100, -16, 2, 2048) 
pg.init() 
screen = pg.display.set_mode((640, 480)) 

# A list of the music file paths. 
SONGS = ['file1.ogg', 'file2.ogg', 'file3.ogg'] 
# Here we create a custom event type (it's just an int). 
SONG_FINISHED = pg.USEREVENT + 1 
# When a song is finished, pygame will add the 
# SONG_FINISHED event to the event queue. 
pg.mixer.music.set_endevent(SONG_FINISHED) 
# Load and play the first song. 
pg.mixer.music.load('file1.ogg') 
pg.mixer.music.play(0) 


def main(): 
    clock = pg.time.Clock() 
    song_idx = 0 # The index of the current song. 
    done = False 

    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 
      elif event.type == pg.KEYDOWN: 
       # Press right arrow key to increment the 
       # song index. Modulo is needed to keep 
       # the index in the correct range. 
       if event.key == pg.K_RIGHT: 
        print('Next song.') 
        song_idx += 1 
        song_idx %= len(SONGS) 
        pg.mixer.music.load(SONGS[song_idx]) 
        pg.mixer.music.play(0) 
      # When a song ends the SONG_FINISHED event is emitted. 
      # Then just pick a random song and play it. 
      elif event.type == SONG_FINISHED: 
       print('Song finished. Playing random song.') 
       pg.mixer.music.load(random.choice(SONGS)) 
       pg.mixer.music.play(0) 

     screen.fill((30, 60, 80)) 
     pg.display.flip() 
     clock.tick(30) 


if __name__ == '__main__': 
    main() 
    pg.quit() 
+0

我推薦使用ogg文件而不是mp3,因爲pygame有mp3格式的問題,它也是專有格式,這意味着您可以被迫支付許可證費用。 – skrx

相關問題