Pygame如何获取上一首歌曲

2024-09-27 00:17:45 发布

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

我想让程序去到上一首歌,如果用户决定按下按钮(请注意,我是在树莓派上这样做的)。问题是我不能想出如何使程序到上一首歌。我已经到了下一首歌的时候了,我也试过了游戏机。混音器。音乐.rewind()'但这只会转到当前歌曲的开头。在

def prevSong():
    print("musiclist is ",musiclist)
    print('Playing previous song')
    pygame.mixer.music.rewind()

def nextSong():
    pygame.mixer.init()
    print("musiclist is ",musiclist)
    print('                      ')
    random_song = random.choice(musiclist)
    randSong = pygame.mixer.music.load(random_song)
    print('Playing next song: {}'.format(random_song))
    pygame.mixer.music.play()
    musiclist.remove(random_song)

我希望对prevSong()进行更改。函数nextSong()就是一个例子。有什么建议吗?谢谢

编辑1:好的,我创建了一个名为“prevSongList”的新列表,但是我不知道该如何添加歌曲

^{pr2}$

Tags: 程序songisdefmusicrandom歌曲pygame
2条回答

同意你应该把歌曲保存在一个列表中,你也可以制作一个dj类,这样你就可以扩展它

class DJSongify:

    def __init__(self):
        self.previous = location.music
        self.songlist = []   
    def songlist_continue(self,song)
        self.previous = song
        self.songlist.append(song)

这将允许您跟踪并在DJ类上执行其他操作,例如,如果歌曲列表对于Rasberry Pi来说太大,则对其执行垃圾收集。您甚至可以设置一个歌曲列表限制,并通过这种方式在类中处理它。在

正如您所添加的,您应该创建一个数组来包含所有播放的歌曲。为了能够正确地访问前一个,您还应该有一个变量来告诉您当前在列表中的位置。在

在您的prevSong函数中,您可以在为列表编制索引之前访问歌曲。比如:

def prevSong():
    print("musiclist is ",musiclist)
    print('Playing previous song')
    #you should add a if there in case there is no previous song
    currentIndex  #remove 1 to the current index 
    lastSong = prevSongList[currentIndex]
    #play the song
    pygame.mixer.music.load(lastSong)

在您的nextSong函数中,在添加随机歌曲之前,请检查是否已经有currentIndex+1的歌曲。在

关于你的错误,我想是因为台词

^{pr2}$

我不确定pygame.mixer.music.load(random_song)返回什么,但它可能不是字符串,您应该改用歌曲的名称:

prev = prevSongList.append(random_song)

相关问题 更多 >

    热门问题