Pygame 简明教程

Pygame - Playing Movie

Pygame 在其最新版本中停止了对视频文件的支持。不过,早期版本的 Python 2.7 发行版中仍然可以使用。对于本节,已使用 Pygame 1.9.2 和 Python 2.7.18。

Pygame has discontinued support for video files in its latest version. However, earlier versions on Python 2.7 distributions, it can be still used. For this section, Pygame 1.9.2 and Python 2.7.18 has been used.

pygame.movie 模块支持来自基本编码 MPEG-1 视频文件的播放视频和音频。电影播放发生在后台线程中,这使得播放易于管理。如果要播放电影的声音,则必须对加载和播放声音的 pygame.mixerpygame 模块进行取消初始化。

The pygame.movie module supports playback video and audio from basic encoded MPEG-1 video files. Movie playback happens in background threads, which makes playback easy to manage. the pygame.mixerpygame module for loading and playing sounds module must be uninitialized if the movie’s sound is to be played.

首先通过以下语法来获取电影对象 −

To begin with obtain a Movie object by following syntax −

movie = pygame.movie.Movie('sample.mpg')

Movie 类提供以下方法来控制播放。

The Movie class provides following methods to control playback.

pygame.movie.Movie.play

start playback of a movie

pygame.movie.Movie.stop

stop movie playback

pygame.movie.Movie.pause

temporarily stop and resume playback

pygame.movie.Movie.skip

advance the movie playback position

pygame.movie.Movie.rewind

restart the movie playback

pygame.movie.Movie.get_time

get the current vide playback time

pygame.movie.Movie.get_length

the total length of the movie in seconds

pygame.movie.Movie.get_size

get the resolution of the video

pygame.movie.Movie.has_audio

check if the movie file contains audio

pygame.movie.Movie.set_volume

set the audio playback volume

pygame.movie.Movie.set_display

set the video target Surface

以下代码在 Pygame 显示窗口上播放 .MPG 文件。−

Following code plays a .MPG file on the Pygame display window. −

import pygame

FPS = 60
pygame.init()
clock = pygame.time.Clock()
movie = pygame.movie.Movie('sample_640x360.mpg')
screen = pygame.display.set_mode(movie.get_size())
movie_screen = pygame.Surface(movie.get_size()).convert()

movie.set_display(movie_screen)
movie.play()

playing = True
while playing:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         movie.stop()
         playing = False

   screen.blit(movie_screen,(0,0))
   pygame.display.update()
   clock.tick(FPS)
pygame.quit()