Play Video in Python Using Pygame

In this module, we are going to discuss how to play a video file in Python using pygame. Here, we play a video file in pygame using pygame.movie.

pygame.movie in Python to play video

Here we use pygame.movie.Movie() module for playing a video. The syntax is as follows

pygame.movie.Movie("file name")

The file must be in mpg format else it will not support the playing of file.

The following code gives a complete description of playing a video file

import pygame
import sys
pygame.init()
clo_obj=pygame.time.Clock()
movie=pygame.movie.Movie("movie_sample.mpg")
sur_obj=pygame.display.set_mode(movie.get_size())
mov_scre=pygame.Surface(movie.get_size()).convert()
movie.set_display(mov_scre)
movie.play()
while True:
    for eve in pygame.event.get():
        if eve==pygame.QUIT:
            movie.stop()
            pygame.quit()
            sys.exit()
    sur_obj.blit(mov_scre,(0,0))
    pygame.display.update()
    clo_obj.tick(60)

Output:

We get the screen of size as video and the video starts playing and it continues until it is completed or we close the window.

movie=pygame.movie.Movie("movie_sample.mpg")

It is used for loading mpg files and we assign it with an object called movie which will be used in a further piece of code.

sur_obj=pygame.display.set_mode(movie.get_size())

We are making the screen set to the size of the video file. To get it possible we used movie.get_size() function which returns the (width,height) of video file.

mov_scre=pygame.Surface(movie.get_size()).convert()

pygame.Surface is used for representing images. Here, we are using it to set up a video screen convert() changes the pixel format of the video.

movie.play()

play() is used to start the playing of the video files. By default, it takes input as zero(0) and stops playing when the video is completed but if we specify -1 then the video self-loops it will not end.

movie.stop()

It is a function used to stop playing video files.

Also read:

Change Collision HitBox size with Pygame

One response to “Play Video in Python Using Pygame”

  1. Anonymous says:

    NotImplementedError: movie module not available (ModuleNotFoundError: No module named ‘pygame.movie’)

    I got this error!

Leave a Reply

Your email address will not be published. Required fields are marked *