0

I've been working on a video player in Python using MoviePy and Pygame. While I have managed to get it working, the video playback speed is not as smooth as I would like it to be, especially for high-resolution videos.

Here's my code:

from moviepy.editor import VideoFileClip
import pygame
import sys
import numpy as np

# Initialize pygame
pygame.init()

# Set the dimensions of the screen
screen_width = 640
screen_height = 480

# Create the screen
screen = pygame.display.set_mode((screen_width, screen_height))

# Load the video file
video_file = 'your_video.mp4'
clip = VideoFileClip(video_file)

# Get the video's frames per second (FPS)
fps = clip.fps

# Create a clock to control the frame rate
clock = pygame.time.Clock()

# Play the video
playing = True

def toggle_play():
    nonlocal playing
    playing = not playing

pygame.display.set_caption("Video Player (Press Space to Toggle Play/Pause)")

# Main game loop
frame_idx = 0
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                toggle_play()

    # Clear the screen
    screen.fill((0, 0, 0))

    if playing:
        # Read the frame at the current time
        frame = clip.get_frame(frame_idx / fps)
        frame_idx += 1
    else:
        frame = clip.get_frame(frame_idx / fps)

    if frame_idx >= int(clip.fps * clip.duration):
        frame_idx = 0

    # Convert the MoviePy frame to a NumPy array and resize it
    frame_np = np.array(frame)
    frame_np = pygame.surfarray.make_surface(frame_np.swapaxes(0, 1))

    # Display the frame on the screen
    screen.blit(frame_np, (0, 0))

    pygame.display.flip()
    clock.tick(fps)

# Clean up and quit
pygame.quit()
sys.exit()

I've tried several optimizations, including resizing the frames and using the clock to control the frame rate, but I'm still facing performance issues. The video playback is noticeably slower than I expected.

Is there a more efficient way to improve the video playback speed in this setup? Are there any specific optimizations or libraries that I should consider using for smoother video playback?

Any guidance or suggestions would be greatly appreciated. Thanks in advance!

1 Answers1

-1

Hi I have worked on a similar project, I think you are trying to play a video in pygame,so there are many things to be taken care of if you need video in correct Playback rate.

  • Issue:The reason for the video playback issue is due to the current structure of the program.
  • Reason:In the above code the video conversion & frame extraction & frame conversion & frame transformation are all performed in a while loop.(these operations may take more time to complete/finish),Thus it takes more time to render and Thus the video sync with fps is lost and video plays in wrong Playback rate.
  • Solution:create a separate thread for loading all the frames and perform the transformations/conversions etc. in that thread(or you can use multiprocessing) and in the while loop of main process(ie pygame loop), sync the loop to fps of video so that the video runs in correct fps.(in this only loop get the current frame from preloaded array/list of frames and render it on pygame window/surface)

For future reference

  • If there is a need for Audio support then another thread to load the audio should be performed. Additional Modules
  • av,imageio,PIL etc libraries are very effective in such tasks,also opencv(aka cv2) also can be used(but cv2 is large in size if packages as .exe)
  • if you just need a video player inside pygame check pypi:mpv-python or vlc
  • Also if possible reducing the additional transformations on frames will also help in faster frame load.
cool-guy
  • 3
  • 1