我有 4 个视频文件(电影的不同场景)。
当我运行播放器时,将播放一个起始场景。 在该场景结束之前,假设视频播放器从外部文件读取一个 int 值 (0-100)(所有这些都在运行时发生),并且根据该 int 值,它必须确定接下来要播放哪个场景。
伪示例:
if (x > 0 && x < 30)
videoSource = scene2
else if (x >= 30 && x < 60)
videoSource = scene3
else if (x >= 60 && x <= 100)
videoSource = scene 4
如何让它根据该变量在运行时更改视频源?
我不关心视频文件的格式,(Avi、mp4...)任何有效的都可以。
我不知道如何解决这个问题。我一直在寻找有可能实现这一目标的东西,例如 pyglet或GStreamer ,但我没有找到明确的解决方案。
编辑:我有基本的播放器和带有 pyglet 的视频播放器,并且我能够使用以下代码播放视频而不依赖于变量:
import pyglet
vidPath="sample.mpg"
window = pyglet.window.Window()
player = pyglet.media.Player()
source = pyglet.media.StreamingSource()
MediaLoad = pyglet.media.load(vidPath)
player.queue(MediaLoad)
player.play()
@window.event
def on_draw():
window.clear()
if player.source and player.source.video_format:
player.get_texture().blit(0,0)
pyglet.app.run()
我该如何解决这个问题?我们将非常感谢正确方向的指导和/或一些示例代码。
提前致谢。
最佳答案
根据评论修改答案
如果您的目标是不断读取正在从另一个进程的输出接收写入的文件,则有几个方面需要解决...
- 您要么需要定期读取不断被覆盖的文件,要么需要尾部附加新值的文件的输出。
- 当您启动 pyglet 事件循环时,您的脚本当前会阻塞,因此此文件检查必须在不同的线程中进行,然后您必须传达更新事件。
我无法完全评论步骤 2,因为我从未使用过 pyglet,也不熟悉它如何使用事件或信号。但我至少可以用线索建议其中一半。
这是一个使用线程读取文件并在找到行时报告的 super 基本示例:
import time
from threading import Thread
class Monitor(object):
def __init__(self):
self._stop = False
def run(self, inputFile, secs=3):
self._stop = False
with open(inputFile) as monitor:
while True:
line = monitor.readline().strip()
if line.isdigit():
# this is where you would notify somehow
print int(line)
time.sleep(secs)
if self._stop:
return
def stop(self):
self._stop = True
if __name__ == "__main__":
inputFile = "write.txt"
monitor = Monitor()
monitorThread = Thread(target=monitor.run, args=(inputFile, 1))
monitorThread.start()
try:
while True:
time.sleep(.25)
except:
monitor.stop()
代码末尾的 sleep 循环只是模拟事件循环和 block 的一种方法。
这是一个测试来展示它是如何工作的。首先,我打开一个 python shell 并打开一个新文件:
>>> f = open("write.txt", 'w+', 10)
然后就可以启动这个脚本了。返回 shell,您可以开始编写以下行:
>>> f.write('50\n'); f.flush()
在您的脚本终端中,您将看到它读取并打印这些行。
另一种方法是,如果写入此文件的进程不断覆盖它,您只需通过设置 monitor.seek(0)
并调用 readline() 来重新读取该文件。
这又是一个非常简单的示例,可以帮助您入门。我确信有更先进的方法可以解决这个问题。下一步是弄清楚如何向 pyglet 事件循环发送信号以调用将更改视频源的方法。
更新
您应该查看 pyglet 文档的这一部分,了解如何创建自己的事件调度程序:http://pyglet.org/doc/programming_guide/creating_your_own_event_dispatcher.html
同样,如果对 pyglet 没有太多了解,它可能如下所示:
class VideoNotifier(pyglet.event.EventDispatcher):
def updateIndex(self, value):
self.dispatch_events('on_update_index', value)
VideoNotifier.register_event('on_update_index')
videoNotifier = VideoNotifier()
@videoNotifier.event
def on_update_index(newIndex):
# thread has notified of an update
# Change the video here
pass
对于您的线程类,您将传入调度程序实例,并使用 updateIndex() 事件来通知:
class Monitor(object):
def __init__(self, dispatcher):
self._stop = False
self._dispatcher = dispatcher
def run(self, inputFile, secs=3):
...
...
# should notify video of new value
line = int(line_from_file)
self._dispatcher.updateIndex(line)
...
...
希望这能让您开始!
关于python - 根据运行时变量的值播放不同的视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9456386/