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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值