我想使用vlc python API浏览youtube视频并每10秒拍摄一次快照。
使用当前方法,我遇到了问题,因为我必须依靠播放器更新其显示图像的速度。发生的速度是不可预测的。我认为,最好的办法是在播放器显示新图像时触发事件。然后我可以对此做出反应,而不必对time.sleep()
感到困惑。
目前,我一直等到收到带有时间戳的视频缓冲包,以确保播放器可以按所需的时间戳显示图像。
首先,我实例化播放器并等待它出现在屏幕上(需要一个事件)。然后,循环以截屏开始。
import pafy
import vlc
import os
import time
url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
video = pafy.new(url)
best = video.getbest()
playurl = best.url
skipTime = 1000*10*10 # milliseconds
directory = "images/"
prefix = str.split(url, "=")[1] + "_" # get video ID, end of url
harvesting = False
waitForBuffer = False
recordTime = 0
def callbackBuffering(arg):
global waitForBuffer
global harvesting
if(recordTime + skipTime < arg.u.new_time and harvesting):
waitForBuffer = False
try:
os.mkdir("images")
except:
print("directory exists")
Instance = vlc.Instance()
player = Instance.media_player_new()
eventManager = player.event_manager()
eventManager.event_attach(vlc.EventType.MediaPlayerBuffering, callback = callbackBuffering)
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()
time.sleep(5) # wait till the window appears
player.pause()
images = 0
harvesting = True
while(player.get_time() < player.get_length()):
waitForBuffer = True
path = directory + prefix + str(player.get_time() )
print("image will be taken at " + str(player.get_time() ) + "ms at path "+ path )
time.sleep(0.5)
recordTime = player.get_time()
player.video_take_snapshot(0, directory + prefix + str(recordTime) ,i_width=player.video_get_width(), i_height=player.video_get_height())
player.set_time(recordTime+skipTime)
while(waitForBuffer):
print("waiting for buffering")
time.sleep(0.1)
答案 0 :(得分:0)
尝试EventType.MediaPlayerPositionChanged
或EventType.MediaPlayerTimeChanged
它们似乎都基于每秒计数来工作。
他们也很高兴地处理了等待视频加载的问题,因为在显示内容之前,时间和位置都不会改变