在第一首歌曲结束后如何安排音频文件在pygame中自动播放?

时间:2017-08-09 16:36:50

标签: python 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 个答案:

答案 0 :(得分:1)

将您的音乐文件(路径)放入列表,定义自定义使用问题并调用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()