我正在编写一个脚本,启动时会按编号播放视频。然后,在播放结束后,脚本会询问下次播放的视频编号,依此类推。我在 PyQT5 中使用 VLC python。
import sys
import time
import vlc
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt
class Player(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Player, self).__init__(parent)
self.setWindowTitle("Media Player")
# creating a basic vlc instance
self.instance = vlc.Instance(['--video-on-top'])
self.instance.log_unset()
self.media=None
self.mediaplayer = self.instance.media_player_new()
self.create_ui()
self.open_file()
def create_ui(self):
self.videoframe = QtWidgets.QFrame(
frameShape=QtWidgets.QFrame.Box, frameShadow=QtWidgets.QFrame.Raised)
if sys.platform.startswith("linux"): # for Linux using the X Server
self.mediaplayer.set_xwindow(self.videoframe.winId())
elif sys.platform == "win32": # for Windows
self.mediaplayer.set_hwnd(self.videoframe.winId())
elif sys.platform == "darwin": # for MacOS
self.mediaplayer.set_nsobject(self.videoframe.winId())
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
self.setWindowFlags(Qt.FramelessWindowHint)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.videoframe)
def play(self):
if self.mediaplayer.play() == -1:
self.open_file()
self.mediaplayer.play()
def open_file(self):
numberfile = input("Number file: ")
filename = (f"/home/Tadont/Video/{numberfile}.mp4")
self.media = self.instance.media_new(filename)
self.mediaplayer.set_media(self.media)
self.eventManager=self.mediaplayer.event_manager()
self.eventManager.event_attach(vlc.EventType.MediaPlayerEndReached, self.next_file)
self.play()
def next_file(self, event):
if event.type == vlc.EventType.MediaPlayerEndReached:
#self.mediaplayer.stop()
self.open_file()
def main():
app = QtWidgets.QApplication(sys.argv)
player = Player()
player.show()
player.move(1, 1)
player.resize(406, 86)
player.setObjectName("MainWindow")
player.setStyleSheet("#MainWindow{background-color:black}")
sys.exit(app.exec_())
if __name__ == "__main__":
main()
我有第一个文件要播放,然后我写入第二个播放的文件编号,但第二个文件没有开始。如何解决这个问题?
我想我没有新的
self.media
这是因为 VLC
MediaPlayerEndReached
事件的回调将在工作线程上运行,而不是在主线程上运行。因此,使用线程间信号机制或postEvent()
。
这是后者的一个例子。
...
from PyQt5.QtCore import QCoreApplication, QEvent
...
class Player(QtWidgets.QMainWindow):
...
def open_file(self):
....
self.eventManager=self.mediaplayer.event_manager()
self.eventManager.event_attach(vlc.EventType.MediaPlayerEndReached,
lambda _: QCoreApplication.postEvent(self, QEvent(QEvent.User))
self.play()
def customEvent(self, event):
# You need to dispatch if you use custom events for other cases.
self.open_file()
...