600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python 定时播放音乐_python – 如何在第一首歌曲结束后安排音频文件在pygame中自动播放?...

python 定时播放音乐_python – 如何在第一首歌曲结束后安排音频文件在pygame中自动播放?...

时间:2018-11-25 06:28:44

相关推荐

python 定时播放音乐_python – 如何在第一首歌曲结束后安排音频文件在pygame中自动播放?...

将您的音乐文件(路径)放入列表,定义自定义使用事件并调用

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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。