PYGLET——媒体播放器
在本文中,我们将看到如何在Python中的 PYGLET 模块中创建一个简单的媒体播放器。 Pyglet 是一个易于使用但功能强大的库,用于开发视觉丰富的 GUI 应用程序,如游戏、多媒体等。窗口是占用操作系统资源的“重量级”对象。 Windows 可能显示为浮动区域,也可以设置为填充整个屏幕(全屏)。为了加载文件,即资源,我们使用 pyglet 的资源模块。该模块允许应用程序指定资源的搜索路径。 Pyglet 可以播放 WAV 文件,如果安装了 FFmpeg,还有很多其他的音频和视频格式。播放由 Player 类处理,该类从 Source 对象读取原始数据并提供暂停、搜索、调整音量等方法。 Player 类实现了最好的可用音频设备。
我们可以在下面给出的命令的帮助下创建一个窗口和播放器对象
# creating a window
window = pyglet.window.Window(width, height, title)
# creating a player for media
player = pyglet.media.Player()
In order to play a media in pyglet we have to do the following
1. Create pyglet window
2. Create a player object
3. Load the media by player from the path of media
4. Add loaded media in the queue of player
5. Play the video
6. Create a key press event handler which is used to pause and resume the video
下面是实现
Python3
# importing pyglet module
import pyglet
# width of window
width = 500
# height of window
height = 500
# caption i.e title of the window
title = "Geeksforgeeks"
# creating a window
window = pyglet.window.Window(width, height, title)
# video path
vidPath ="media.mp4"
# creating a media player object
player = pyglet.media.Player()
# creating a source object
source = pyglet.media.StreamingSource()
# load the media from the source
MediaLoad = pyglet.media.load(vidPath)
# add this media in the queue
player.queue(MediaLoad)
# play the video
player.play()
# on draw event
@window.event
def on_draw():
# clea the window
window.clear()
# if player source exist
# and video format exist
if player.source and player.source.video_format:
# get the texture of video and
# make surface to display on the screen
player.get_texture().blit(0, 0)
# key press event
@window.event
def on_key_press(symbol, modifier):
# key "p" get press
if symbol == pyglet.window.key.P:
# printing the message
print("Key : P is pressed")
# pause the video
player.pause()
# printing message
print("Video is paused")
# key "r" get press
if symbol == pyglet.window.key.R:
# printing the message
print("Key : R is pressed")
# resume the video
player.play()
# printing message
print("Video is resumed")
# run the pyglet application
pyglet.app.run()
输出 :
Key : P is pressed
Video is paused
Key : R is pressed
Video is resumed
Key : P is pressed
Video is paused
Key : R is pressed
Video is resumed