检查歌曲是否已在pygame中播放完毕

2024-04-25 01:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法判断一首歌是否已经在pygame中播放完毕

代码如下:

from tkinter import *
import pygame

root = Tk()
pygame.init()

def play():
    pygame.mixer.music.load("test.ogg")
    pygame.mixer.music.play(loops = 0)

def pause():
    global paused
    if paused == False:
        pygame.mixer.music.pause()
        paused = True
    elif paused:
        pygame.mixer.music.unpause()
        paused = False

def check_if_finished():
    if pygame.mixer.music.get_busy():
        print("Song is not finished")
    else:
        print("Song is finshed")

paused = False

play_button = Button(root , text = "Play Song" , command = play)
play_button.grid(row = 0 , column = 0)

pause_button = Button(root , text = "Pause Song" , command = pause)
pause_button.grid(row = 1 , column = 0 , pady = 15)

check_button = Button(root , text = "Check" , command = check_if_finished)
check_button.grid(row = 2 , column = 0)

mainloop()

在这里,我使用了pygame.mixer.music.get_busy()函数来检查歌曲是否已完成,但问题是check_if_finished()函数在我暂停歌曲时没有提供预期的输出。我想要的是在暂停歌曲时不要打印"The song is finished"

在pygame中有什么方法可以实现这一点吗

如果有人能帮我,那就太好了


Tags: falseplayifsongisdefcheckmusic
1条回答
网友
1楼 · 发布于 2024-04-25 01:18:56

What I want is to not print "The song is finished" when I pause the song.

你说得对。见^{}

Returns True when the music stream is actively playing. When the music is idle this returns False. In pygame 2.0.1 and above this function returns False when the music is paused.

您只需添加一个附加条件即可解决此问题:

def check_if_finished():

    if paused or pygame.mixer.music.get_busy():
        print("Song is not finished")
    else:
        print("Song is finshed")`

相关问题 更多 >