我正在尝试播放和停止媒体。当我单击“停止”时,播放器停止并清除列表框中的选择。当我再次点击播放按钮时,无论我在哪里停止音频,媒体都会播放。 为了清楚起见,停止是暂停。它没有清除队列 这是我的代码。我不想更改 pyglet 库。
class TestSeekBar():
toggle_play_stop = itertools.cycle(["play", "stop"])
def __init__(self):
root = tk.Tk()
root.bind("<<SeekbarPositionChanged>>", self.seek_new_position)
frame = tk.Frame(root)
frame.grid(row=1, pady=10, padx=10)
c = Seekbar(
frame, background="blue", width=360, height=10)
c.grid(row=2, columnspan=10, sticky='ew', padx=5)
self.add_file_image = tk.PhotoImage(file="icons/add_file.gif")
self.add_file = tk.Button(frame, image=self.add_file_image, command=self.add_file)
self.add_file.grid(row=3)
self.audio_list_box = tk.Listbox(frame)
self.audio_list_box.grid(row=4)
self.play_image = tk.PhotoImage(file="icons/play.gif")
self.stop_image = tk.PhotoImage(file="icons/stop.gif")
self.play_stop_btn = tk.Button(frame, image=self.play_image, command=self.play_stop)
self.play_stop_btn.image = self.play_image
self.play_stop_btn.grid(row=3, column=2)
self.audio_time = tk.Label(frame, text="00.00")
self.audio_time.grid(row=1, column=2)
of_label = tk.Label(frame, text="of")
of_label.grid(row=1, column=3)
self.audio_total_length = tk.Label(frame, text="00.00")
self.audio_total_length.grid(row=1, column=4)
self.player = pyglet.media.Player()
root.mainloop()
def seek_new_position(self, event):
print("Dragged to x:", event.x)
def add_file(self):
audios = filedialog.askopenfilenames()
for audio in audios:
path = os.path.split(audio)
audio = path[1]
self.audio_list_box.insert(END, audio)
self.path = f'{path[0]}/'
print(self.path)
def play_stop(self):
action = next(self.toggle_play_stop)
if action == "play":
try:
self.current_track_index = self.audio_list_box.curselection()[0]
except IndexError:
self.current_track_index = 0
self.play()
elif action == "stop":
self.stop_play()
def play(self):
self.audio = self.audio_list_box.get(ACTIVE)
self.play_stop_btn.config(image=self.stop_image)
self.source = pyglet.media.load(self.audio)
self.player.queue(self.source)
self.get_audio_length()
self.player.play()
def stop_play(self):
self.play_stop_btn.config(image=self.play_image)
self.audio_list_box.selection_clear(ACTIVE)
self.audio_total_length.config(text="00.00")
self.stop()
def stop(self):
self.reset_player()
def reset_player(self):
self.player.pause()
self.player.delete()