首页 > 解决方案 > 如果用户未按下任何键,如何自动播放播放列表中的下一首歌曲?

问题描述

我想为用户提供播放、暂停、播放下一首或上一首歌曲的选项。如果用户没有按下任何按钮,列表中的下一首歌曲应该会自动播放。目前,该程序因用户输入而暂停。

我尝试在另一个线程中播放歌曲并等待用户在主线程中输入选择。但问题是主线程在播放下一首歌曲之前等待用户的输入。

def music(file):
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()
    try:
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(0)
    except:
        pass

def pause():
    print(file + " paused")
    pygame.mixer.music.pause()
    global set
    set = 1

def playsong():
    global set
    global t1
    print ("Playing song named : " + file)
    if file != "" and set==0:
        t1 = threading.Thread(target = music ,args=(file,))
        t1.setName("audio bajao")
        t1.start()
ch = 1
song_list = ["song1.mp3","song2.mp3"]
while((i < len(song_list)) and (ch != 5) ):
    ch = input("Enter choice ")
    file = song_list[i]
    if(ch == 1):
        playsong()
    elif(ch == 2):
        ch = 1
        pause()
    elif(ch == 3):
        #play previous song
        ch = 1
        i -= 2
    elif (ch == 4):
        #play next song
        ch = 1
    elif (ch == 5):
        break
    i += 1

如果用户未按下任何键,我希望程序在歌曲结束时播放列表中的下一首歌曲。它不应该再次要求用户按下播放键来播放下一首歌曲。

标签: pythonpygame

解决方案


你可以试试pygame.mixer.get_busy()

为了实现这一点,添加某种计时器变量,我个人更喜欢滴答计数器,所以......

inactive_ticks = 0

之后,在您的主事件循环中,用于pygame.mixer.get_busy()检查是否正在播放音乐,然后...

if not pygame.mixer.get_busy():
    inactive_ticks += 1

    if inactive_ticks == 100:
        # Play the next song
        inactive_ticks = 0

那应该行得通。


推荐阅读