Skip to main content
 首页 » 编程设计

python之如果用户没有按下任何键,如何自动播放播放列表中的下一首歌曲

2024年11月24日7lonelyxmas

我想为用户提供播放、暂停、播放下一首或上一首歌曲的选项。如果用户什么都不按,列表中的下一首歌曲应该会自动播放。目前程序暂停以等待用户输入。

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

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 

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

请您参考如下方法:

你可以试试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 

这应该有效。