Home Backend Development Python Tutorial Video player function implemented in Python

Video player function implemented in Python

Jun 01, 2018 pm 04:33 PM
python Function player

This article mainly introduces the video player function implemented in Python, and analyzes the related operating skills of Python based on the pyglet library to implement the video playback function in the form of a complete example. Friends in need can refer to the examples in this article

Describes the video player function implemented in Python. Share it with everyone for your reference, the details are as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

# -*- coding:utf-8 -*-

#! python3

# ----------------------------------------------------------------------------

# pyglet

# Copyright (c) 2006-2008 Alex Holkner

# All rights reserved.

#

# Redistribution and use in source and binary forms, with or without

# modification, are permitted provided that the following conditions

# are met:

#

# * Redistributions of source code must retain the above copyright

#  notice, this list of conditions and the following disclaimer.

# * Redistributions in binary form must reproduce the above copyright

#  notice, this list of conditions and the following disclaimer in

#  the documentation and/or other materials provided with the

#  distribution.

# * Neither the name of pyglet nor the names of its

#  contributors may be used to endorse or promote products

#  derived from this software without specific prior written

#  permission.

#

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS

# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT

# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS

# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE

# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,

# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,

# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;

# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER

# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT

# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN

# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE

# POSSIBILITY OF SUCH DAMAGE.

# ----------------------------------------------------------------------------

'''Audio and video player with simple GUI controls.

'''

__docformat__ = 'restructuredtext'

__version__ = '$Id: $'

import sys

from pyglet.gl import *

import pyglet

from pyglet.window import key

def draw_rect(x, y, width, height):

  glBegin(GL_LINE_LOOP)

  glVertex2f(x, y)

  glVertex2f(x + width, y)

  glVertex2f(x + width, y + height)

  glVertex2f(x, y + height)

  glEnd()

class Control(pyglet.event.EventDispatcher):

  x = y = 0

  width = height = 10

  def __init__(self, parent):

    super(Control, self).__init__()

    self.parent = parent

  def hit_test(self, x, y):#点中控件

    return (self.x < x < self.x + self.width and

        self.y < y < self.y + self.height)

  def capture_events(self):

    self.parent.push_handlers(self)

  def release_events(self):

    self.parent.remove_handlers(self)

class Button(Control):

  charged = False

  def draw(self):

    if self.charged:

      glColor3f(0, 1, 0)

    draw_rect(self.x, self.y, self.width, self.height)

    glColor3f(1, 1, 1)

    self.draw_label()

  def on_mouse_press(self, x, y, button, modifiers):

    self.capture_events()

    self.charged = True

  def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):

    self.charged = self.hit_test(x, y)

  def on_mouse_release(self, x, y, button, modifiers):

    self.release_events()

    if self.hit_test(x, y):

      self.dispatch_event(&#39;on_press&#39;)

    self.charged = False

Button.register_event_type(&#39;on_press&#39;)#注册事件

class TextButton(Button):

  def __init__(self, *args, **kwargs):

    super(TextButton, self).__init__(*args, **kwargs)

    self._text = pyglet.text.Label(&#39;&#39;, anchor_x=&#39;center&#39;, anchor_y=&#39;center&#39;)

  def draw_label(self):

    self._text.x = self.x + self.width / 2

    self._text.y = self.y + self.height / 2

    self._text.draw()

  def set_text(self, text):

    self._text.text = text

  text = property(lambda self: self._text.text,

          set_text)

class Slider(Control):

  THUMB_WIDTH = 6

  THUMB_HEIGHT = 10

  GROOVE_HEIGHT = 2

  def draw(self):

    center_y = self.y + self.height / 2

    draw_rect(self.x, center_y - self.GROOVE_HEIGHT / 2,

         self.width, self.GROOVE_HEIGHT)

    pos = self.x + self.value * self.width / (self.max - self.min)

    draw_rect(pos - self.THUMB_WIDTH / 2, center_y - self.THUMB_HEIGHT / 2,

         self.THUMB_WIDTH, self.THUMB_HEIGHT)

  def coordinate_to_value(self, x):#改变进度

    return float(x - self.x) / self.width * (self.max - self.min) + self.min

  def on_mouse_press(self, x, y, button, modifiers):

    value = self.coordinate_to_value(x)

    self.capture_events()

    self.dispatch_event(&#39;on_begin_scroll&#39;)

    self.dispatch_event(&#39;on_change&#39;, value)

  def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):

    value = min(max(self.coordinate_to_value(x), self.min), self.max)

    self.dispatch_event(&#39;on_change&#39;, value)

  def on_mouse_release(self, x, y, button, modifiers):

    self.release_events()

    self.dispatch_event(&#39;on_end_scroll&#39;)

Slider.register_event_type(&#39;on_begin_scroll&#39;)

Slider.register_event_type(&#39;on_end_scroll&#39;)

Slider.register_event_type(&#39;on_change&#39;)

class PlayerWindow(pyglet.window.Window):

  GUI_WIDTH = 400

  GUI_HEIGHT = 40

  GUI_PADDING = 4#按钮间隔

  GUI_BUTTON_HEIGHT = 16

  def __init__(self, player):

    super(PlayerWindow, self).__init__(caption=&#39;Media Player&#39;,

                      visible=False,

                      resizable=True)

    self.player = player

    self.player.push_handlers(self)

    self.player.eos_action = self.player.EOS_PAUSE

    self.slider = Slider(self)

    self.slider.x = self.GUI_PADDING#类变量

    self.slider.y = self.GUI_PADDING * 2 + self.GUI_BUTTON_HEIGHT

    self.slider.on_begin_scroll = lambda: player.pause()

    self.slider.on_end_scroll = lambda: player.play()

    self.slider.on_change = lambda value: player.seek(value)

    self.play_pause_button = TextButton(self)

    self.play_pause_button.x = self.GUI_PADDING

    self.play_pause_button.y = self.GUI_PADDING

    self.play_pause_button.height = self.GUI_BUTTON_HEIGHT

    self.play_pause_button.width = 45

    self.play_pause_button.on_press = self.on_play_pause

    win = self#自有妙用

    self.window_button = TextButton(self)

    self.window_button.x = self.play_pause_button.x + \

                self.play_pause_button.width + self.GUI_PADDING

    self.window_button.y = self.GUI_PADDING

    self.window_button.height = self.GUI_BUTTON_HEIGHT

    self.window_button.width = 90

    self.window_button.text = &#39;Windowed&#39;

    self.window_button.on_press = lambda: win.set_fullscreen(False)#注意不能写self

    self.controls = [

      self.slider,

      self.play_pause_button,

      self.window_button,

    ]

    x = self.window_button.x + self.window_button.width + self.GUI_PADDING

    i = 0

    for screen in self.display.get_screens():

      screen_button = TextButton(self)

      screen_button.x = x

      screen_button.y = self.GUI_PADDING

      screen_button.height = self.GUI_BUTTON_HEIGHT

      screen_button.width = 80

      screen_button.text = &#39;Screen %d&#39; % (i + 1)

      screen_button.on_press = \

        (lambda s: lambda: win.set_fullscreen(True, screen=s))(screen)

      self.controls.append(screen_button)

      i += 1

      x += screen_button.width + self.GUI_PADDING

  def on_eos(self):

    self.gui_update_state()

  def gui_update_source(self):

    if self.player.source:

      source = self.player.source

      self.slider.min = 0.

      self.slider.max = source.duration

    self.gui_update_state()

  def gui_update_state(self):

    if self.player.playing:

      self.play_pause_button.text = &#39;Pause&#39;

    else:

      self.play_pause_button.text = &#39;Play&#39;

  def get_video_size(self):

    if not self.player.source or not self.player.source.video_format:

      return 0, 0

    video_format = self.player.source.video_format

    width = video_format.width

    height = video_format.height

    if video_format.sample_aspect > 1:

      width *= video_format.sample_aspect

    elif video_format.sample_aspect < 1:

      height /= video_format.sample_aspect

    return width, height

  def set_default_video_size(self):

    &#39;&#39;&#39;Make the window size just big enough to show the current

    video and the GUI.&#39;&#39;&#39;

    width = self.GUI_WIDTH

    height = self.GUI_HEIGHT

    video_width, video_height = self.get_video_size()

    width = max(width, video_width)

    height += video_height

    self.set_size(int(width), int(height))

  def on_resize(self, width, height):

    &#39;&#39;&#39;Position and size video image.&#39;&#39;&#39;

    super(PlayerWindow, self).on_resize(width, height)

    self.slider.width = width - self.GUI_PADDING * 2

    height -= self.GUI_HEIGHT

    if height <= 0:

      return

    video_width, video_height = self.get_video_size()

    if video_width == 0 or video_height == 0:

      return

    display_aspect = width / float(height)

    video_aspect = video_width / float(video_height)

    if video_aspect > display_aspect:

      self.video_width = width

      self.video_height = width / video_aspect

    else:

      self.video_height = height

      self.video_width = height * video_aspect

    self.video_x = (width - self.video_width) / 2

    self.video_y = (height - self.video_height) / 2 + self.GUI_HEIGHT

  def on_mouse_press(self, x, y, button, modifiers):

    for control in self.controls:

      if control.hit_test(x, y):

        control.on_mouse_press(x, y, button, modifiers)

  def on_key_press(self, symbol, modifiers):

    if symbol == key.SPACE:

      self.on_play_pause()

    elif symbol == key.ESCAPE:

      self.dispatch_event(&#39;on_close&#39;)

  def on_close(self):

    self.player.pause()

    self.close()

  def on_play_pause(self):

    if self.player.playing:

      self.player.pause()

    else:

      if self.player.time >= self.player.source.duration:#如果放完了

        self.player.seek(0)

      self.player.play()

    self.gui_update_state()

  def on_draw(self):

    self.clear()

    # Video

    if self.player.source and self.player.source.video_format:

      self.player.get_texture().blit(self.video_x,

                      self.video_y,

                      width=self.video_width,

                      height=self.video_height)

    # GUI

    self.slider.value = self.player.time

    for control in self.controls:

      control.draw()

if __name__ == &#39;__main__&#39;:

  if len(sys.argv) < 2:

    print(&#39;Usage: media_player.py <filename> [<filename> ...]&#39;)

    sys.exit(1)

  for filename in sys.argv[1:]:

    player = pyglet.media.Player()

    window = PlayerWindow(player)

    source = pyglet.media.load(filename)

    player.queue(source)

    window.gui_update_source()

    window.set_default_video_size()

    window.set_size(400,400)

    window.set_visible(True)

    window.gui_update_state()

    player.play()

  pyglet.app.run()

Copy after login

Related recommendations:

Use Python to implement the video download function Example code


##

The above is the detailed content of Video player function implemented in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

GitLab's plug-in development guide on Debian GitLab's plug-in development guide on Debian Apr 13, 2025 am 08:24 AM

Developing a GitLab plugin on Debian requires some specific steps and knowledge. Here is a basic guide to help you get started with this process. Installing GitLab First, you need to install GitLab on your Debian system. You can refer to the official installation manual of GitLab. Get API access token Before performing API integration, you need to get GitLab's API access token first. Open the GitLab dashboard, find the "AccessTokens" option in the user settings, and generate a new access token. Will be generated

What service is apache What service is apache Apr 13, 2025 pm 12:06 PM

Apache is the hero behind the Internet. It is not only a web server, but also a powerful platform that supports huge traffic and provides dynamic content. It provides extremely high flexibility through a modular design, allowing for the expansion of various functions as needed. However, modularity also presents configuration and performance challenges that require careful management. Apache is suitable for server scenarios that require highly customizable and meet complex needs.

See all articles