我正在尝试使用python-vlc
lib构建一个简单的媒体播放器。另外,我试图在一个单独的线程中运行它,以便可以同时运行其他任务。
现在,我很难让播放器实际播放整个播放列表。但是现在,一旦播放列表结束,就会触发线程事件,这使我无法在实际播放期间访问播放器来执行诸如“向前跳过一首歌曲”,“设置音量”之类的任务。
我对线程不是很熟悉,因此想知道设置这一最佳解决方案是什么。
# import built-in modules
from itertools import count
import os
from threading import Event, Thread
# import third-party modules
import vlc
class Player:
def __init__(self):
self.played = count()
self.finished = Event()
vlc_instance = vlc.Instance()
self.media_player = vlc_instance.media_player_new()
self.media_list = vlc_instance.media_list_new()
self.media_list_player = vlc_instance.media_list_player_new()
self.media_list_player.set_media_player(self.media_player)
event_manager = self.media_player.event_manager()
event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, self.end_reached)
def add_media(self, filename):
self.media_list.add_media(filename)
def play(self):
self.media_list_player.set_media_list(self.media_list)
self.media_list_player.play()
def previous(self):
self.media_list_player.previous()
def next(self):
self.media_list_player.next()
def wait(self):
self.finished.wait()
def end_reached(self, event):
if event.type.value == vlc.EventType.MediaPlayerEndReached.value:
if next(self.played) == self.media_list.count():
self.finished.set()
def start_up(directory):
player = Player()
for track in os.listdir(directory):
path = os.path.join(directory, track)
player.add_media(path)
player.play()
#this keeps the thread alive until the event is set to True
player.wait()
if __name__ == '__main__':
directory = '/path/to/music/folder'
x = Thread(target=start_up, args=[directory])
x.start()