我正在尝试通过pyglet在Python 3中播放歌曲。我可以播放和停止一首歌,但是当我尝试播放下一首歌时会产生错误。 I followed these instructions.我将在tkinter中执行该程序。
我的代码:
import pyglet
import glob
from tkinter import Tk, Button
songs=glob.glob("*.mp3")
player=pyglet.media.Player()
def play_song():
global player
for i in range(len(songs)):
source=pyglet.resource.media(songs[i])
player.queue(source)
player.play()
def pause_song():
player.pause()
def next_song():
player.next()
window=Tk()
play_=Button(text="play", command=play_song)
play_.pack()
pause_=Button(text="pause", command=pause_song)
pause_.pack()
next_=Button(text="next", command=next_song)
next_.pack()
window.mainloop()
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__
return self.func(*args)
File "C:\Documents and Settings\Fany\Dokumenty\Hudba\Sabaton\2012 - Carolus Rex\py.py", line 15, in next_song
player.next()
AttributeError: 'Player' object has no attribute 'next'
答案 0 :(得分:0)
尝试对next_song()
进行以下更改def next_song():
player.next_source()
<强>原因强>
请参阅本页
https://pyglet.readthedocs.org/en/pyglet-1.2-maintenance/api/pyglet/media/pyglet.media.Player.html#pyglet.media.Player.time
你会发现 next()是&#34;已弃用&#34;并建议使用 next_source()而不是
HTH
PS 当我在我的机器上测试你的片段时,它有效。
答案 1 :(得分:0)
您可以使用os模块,或者只看播放下一首歌曲的过程,我认为这可能对许多可能使用os模块或其他任何人使用全局变量播放下一首歌曲的人有所帮助
from tkinter import *
import os
root = Tk()
root.geometry("500x500")
root.title("music player ")
Label(root, text="MUSIC PLAYER").pack()
i=0
def prev():
pass
def paly():
music_dir = 'D:\songs'
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[0]))
def nxt():
global i
music_dir = 'D:\songs'
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[i]))
i=i+1
f1=Frame(root).pack()
Button(f1,text="prev",command=prev).pack(side=LEFT,padx=30)
Button(f1,text="play/pause",command=paly).pack(side=LEFT,padx=30)
Button(f1,text="next",command=nxt).pack(side=LEFT,padx=30)
root.mainloop()