Playing a movie (Intermediate)

Most commercial games these days have small movie clips that try to explain the plot to us. For instance, a first-person shooter could have a movie showing a briefing about the next mission. Movie playback is a cool feature to have. Pygame offers limited support for MPEG movies.

Getting ready

We need to have a MPEG movie for this demo. Once you have a movie you can convert it to be used in a Pygame game with the following command:

ffmpeg -i <infile> -vcodec mpeg1video -acodec libmp3lame -intra <outfile.mpg>

Installing ffmpeg and the command-line options are outside the scope of this book, but shouldn't be too difficult (see http://ffmpeg.org/).

How to do it...

The movie playback is set up similarly to the audio playback that we covered in the previous recipe. The following code demonstrates playing a MPEG video. Pay particular attention to the play function:

import pygame, sys
from pygame.locals import *
import time

pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption('Movie Demo')

def play():
    movie = pygame.movie.Movie('out.mpg')
    movie.play()
    TIMEOUT = 7
    pygame.time.delay(TIMEOUT * 1000)
    movie.stop()

while True: 
   screen.fill((255, 255, 255))

   for event in pygame.event.get():
      if event.type == QUIT:
         play()
         pygame.quit()
         sys.exit()

   pygame.display.update()

How it works...

The relevant functions for the movie playback can found in this table:

Function

Description

pygame.movie.Movie('out.mpg')

This function creates a Movie object given the filename of the MPEG movie

movie.play()

This function starts playing the movie

movie.stop()

This function stops playback of the movie

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset