pygame simulaton saved as a mp4 file

Viewed 540

I used pygame to simulate the movement of rain and I was wondering how I can save this simulation as a mp4/gif file because I want to include it in a powerpoint presentation. Is there a function or specific command in other Python packages and libraries I can use besides screenrecording my screen? Thank you!

1 Answers

Directly from only PyGame it's not possible. But you could use the pygame.Surface.save() function to write every frame to a file, e.g.:

import pygame

# Window size
WINDOW_WIDTH  = 400
WINDOW_HEIGHT = 400
WINDOW_FPS    = 30

### initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )

frame_count = 0
exiting     = False
clock       = pygame.time.Clock()
while not exiting:
    # handle events
    # paint the screen

    # save the frame
    frame_count += 1
    filename = "screen_%04d.png" % ( frame_count )
    pygame.image.save( window, filename )

    clock.tick( WINDOW_FPS )  # limit FPS

Then use something like ffmpeg to convert all those still-frames back to an animation:

ffmpeg -r 30 -f image2 -s 400x400 -i screen_%04d.png -vcodec libx264 -crf 25  window_video.mp4

Note the size and frame-rate -r 30 should match the WINDOW_* variables used, and the %04d length of the frame-number match what's output.

Related