文章目录
- 问题描述
- 解决方案
- 参考文献
问题描述
Python快速实现视频播放器,功能有:音画同步、播放暂停、进度条、音量调节
解决方案
安装
pip install pyglet
代码
import sys
import timeimport pyglet
from pyglet.window import key, mousefilename = '1.mp4'
source = pyglet.media.load(filename)
video_format = source.video_format
width, height = video_format.width, video_format.height
title = 'Video Player'
window = pyglet.window.Window(width, height, title, resizable=True)
player = pyglet.media.Player()
player.queue(source)
player.play()@window.event
def on_draw():window.clear()if player.source and player.source.video_format:player.get_texture().blit(0, 0, width=width, height=height)@window.event
def on_resize(_width, _height):global width, heightheight = _width * height / width # 按比例缩放后的高width = _widthdef set_fullscreen():if window.fullscreen:window.set_fullscreen(False)else:window.set_fullscreen(True)@window.event
def on_key_press(symbol, modifier):window.key_begin = time.perf_counter()if symbol == key.SPACE:if player.playing:player.pause()else:player.play()elif symbol == key.ESCAPE:sys.exit()elif symbol == key.ENTER:set_fullscreen()@window.event
def on_key_release(symbol, modifier):def get_key_value():key_duration = time.perf_counter() - window.key_beginkey_value = 1 if key_duration < 0.1 else int(key_duration / 0.1)return key_valueif symbol == key.UP:player.volume = round(player.volume + 0.1 * get_key_value(), 2)print(player.volume)elif symbol == key.DOWN:player.volume = round(player.volume - 0.1 * get_key_value(), 2)if player.volume < 0:player.volume = 0.0print(player.volume)elif symbol == key.LEFT:source.seek(player.time - get_key_value())elif symbol == key.RIGHT:source.seek(player.time + get_key_value())@window.event
def on_mouse_release(x, y, button, modifiers):if button == mouse.LEFT:window.last_mouse_release = (x, y, time.perf_counter())elif button == mouse.MIDDLE:set_fullscreen()@window.event
def on_mouse_press(x, y, button, modifiers):if button == mouse.LEFT and hasattr(window, 'last_mouse_release'):if (x, y) == window.last_mouse_release[:-1]:if time.perf_counter() - window.last_mouse_release[-1] < 0.2:if player.playing:player.pause()else:player.play()pyglet.app.run()
操作
- 左键双击播放暂停
- 中键全屏
- 空格播放暂停
- 上下方向键调节音量
- ESC 退出
- FIXME: 等比调整画面(容易有黑边)
- FIXME: 左右方向键调节进度(容易卡顿,且长按会音画不同步)
参考文献
- pyglet Documentation
- What’s the right way to detect double-click events with python pyglet?