gpt4 book ai didi

python - 我如何使用 pygame.mixer 从列表中选择一首歌曲

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:19 25 4
gpt4 key购买 nike

如何使用pygame选择某首歌曲进行播放?我将它们放入列表中,但以下代码不起作用。当我运行该应用程序时,它打印“无”,当我取消对 pygame.mixer.music.play 的注释时,该应用程序给出错误:“需要一个整数。另外,当我将代码更改为;

    selected_song = random.randint(0,len(songs))
pygame.mixer.music.load(songs[selected_song])

它给出了这个错误:无法从 RWops 读取。所以我想不通。

from tkinter import *
import pygame, os, random
pygame.mixer.init()
songs = (pygame.mixer.music.load("A.mp3"),
pygame.mixer.music.load("B.mp3"),
pygame.mixer.music.load("C.mp3"),
pygame.mixer.music.load("D.mp3"))
window=Tk()
window.geometry("175x150")
class Player:
def __init__(self):
pass
def play(init):
selected_song = random.choice(songs)
#pygame.mixer.music.play(selected_song) #uncomment this
print(selected_song) #comment this
return selected_song

a = Player()
l1=Label(window,text="Music Player",font="times 20")
l1.grid(row=1,column=1)

b1=Button(window,text="Play",width=20,command=a.play)
b1.grid(row=4,column=1)
#b2=Button(window,text="Pause",width=20,command=stop)

#song_list=os.listdir()
#song_listbox=StringVar(window)
#song_listbox.set("select songs")
#menu=OptionMenu(window,song_listbox,*song_list)
#menu.grid(row=4,column=4)
window.mainloop()

最佳答案

pygame.mixer.music.load()将始终返回 None,因此您的 songs 元组将始终是 (None, None, None, None):

pygame.mixer.music.load()

Load a music file for playback

load(filename) -> None
load(object) -> None>

This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.

如果没有必要,阅读您使用的库的文档总是有好处的。


您应该只将文件名存储在歌曲中:

songs = ("A.mp3", "B.mp3", "C.mp3", "D.mp3")

要播放一个随机的音乐文件,做

...
selected_song = random.choice(songs) # select music file
pygame.mixer.music.load(selected_song) # load music file
pygame.mixer.music.play() # play it
...

请注意,这仅在音乐文件位于您启动程序的同一目录中时才有效。

关于python - 我如何使用 pygame.mixer 从列表中选择一首歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com