- 1 year ago
Play videos (with audio) under Python
To play videos with audio in Python, you can use the pygame
library. pygame
is a popular library for writing video games but can also be used to handle multimedia files like videos with audio. If you don't have pygame
installed, you can install it using pip:
bashpip install pygame
Here's a simple example of how you can use pygame
to play videos with audio:
pythonimport pygame
import os
def play_video(video_path):
pygame.init()
# Set the display dimensions to match the video resolution
video_info = pygame.display.Info()
screen = pygame.display.set_mode((video_info.current_w, video_info.current_h))
# Load the video file
try:
video = pygame.movie.Movie(video_path)
except pygame.error:
print("Error loading video:", pygame.get_error())
return
video.set_display(screen)
video.play()
clock = pygame.time.Clock()
while video.get_busy():
for event in pygame.event.get():
if event.type == pygame.QUIT:
video.stop()
pygame.quit()
return
pygame.display.update()
clock.tick(30)
pygame.quit()
if __name__ == "__main__":
video_file = "path/to/your/video.mp4" # Replace this with the path to your video file
play_video(video_file)
Replace "path/to/your/video.mp4"
with the actual path to your video file. This code sets up a Pygame display and plays the video with audio. It will quit when the video finishes or if the user closes the window.
Keep in mind that pygame
has some limitations and might not support all video codecs. If you encounter issues with your video file, consider converting it to a compatible format before playing it with pygame
. Also, for more complex video player requirements, you might want to consider using more specialized libraries like pyglet
or opencv-python
.