如何在 pygame 中加载和播放视频
- 2025-02-14 09:50:00
- admin 原创
- 55
问题描述:
我遇到了一个问题。我想在 pygame 中加载并播放视频,但它没有启动。我看到的唯一东西就是黑屏。这是我的代码:
import pygame
from pygame import display,movie
pygame.init()
screen = pygame.display.set_mode((1024, 768))
background = pygame.Surface((1024, 768))
screen.blit(background, (0, 0))
pygame.display.update()
movie = pygame.movie.Movie('C:Python27.mpg')
mrect = pygame.Rect(0,0,140,113)
movie.set_display(screen, mrect.move(65, 150))
movie.set_volume(0)
movie.play()
你能帮助我吗??
解决方案 1:
该pygame.movie
模块已被弃用并且不再受支持。
如果您只想播放视频,则可以使用MoviePy(另请参阅如何高效使用 MoviePy):
import pygame
import moviepy.editor
pygame.init()
video = moviepy.editor.VideoFileClip("video.mp4")
video.preview()
pygame.quit()
另一种解决方案是使用OpenCVVideoCapture
。安装 Python 版 OpenCV ( cv2 )(请参阅opencv-python)。但是,需要指出的是,它cv2.VideoCapture
不提供从视频文件中读取音频的方法。
这只是显示视频但不播放音频的解决方案。
打开相机进行视频拍摄:
video = cv2.VideoCapture("video.mp4")
从对象获取每秒的帧数VideoCapture
:
fps = video.get(cv2.CAP_PROP_FPS)
创建一个pygame.time.Clock
:
clock = pygame.time.Clock()
抓取视频帧并限制应用程序循环中的每秒帧数:
clock.tick(fps)
success, video_image = video.read()
pygame.Surface
使用以下方法将相机框架转换为物体pygame.image.frombuffer
:
video_surf = pygame.image.frombuffer(video_image.tobytes(), video_image.shape[1::-1], "BGR")
另见视频:
最小示例:
import pygame
import cv2
video = cv2.VideoCapture("video.mp4")
success, video_image = video.read()
fps = video.get(cv2.CAP_PROP_FPS)
window = pygame.display.set_mode(video_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, video_image = video.read()
if success:
video_surf = pygame.image.frombuffer(
video_image.tobytes(), video_image.shape[1::-1], "BGR")
else:
run = False
window.blit(video_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
解决方案 2:
您实际上并没有将其传输到屏幕上。您也没有使用时钟对象,因此它将尽可能快地播放。尝试以下操作:
# http://www.fileformat.info/format/mpeg/sample/index.dir
import pygame
FPS = 60
pygame.init()
clock = pygame.time.Clock()
movie = pygame.movie.Movie('MELT.MPG')
screen = pygame.display.set_mode(movie.get_size())
movie_screen = pygame.Surface(movie.get_size()).convert()
movie.set_display(movie_screen)
movie.play()
playing = True
while playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
movie.stop()
playing = False
screen.blit(movie_screen,(0,0))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
我刚刚从评论中提供的链接中获得了那个 MELT.MPG。你应该能够简单地将该字符串替换为你想要播放的实际 MPG,它就可以工作了……也许吧。
解决方案 3:
您可能知道,该pygame.movie
模块已被弃用,并且不再存在于最新版本的 pygame 中。
另一种方法是逐个读取视频帧,然后使用模块cv2
(OpenCV )将它们blit到pygame屏幕上,可以使用命令提示符命令进行安装:
pip install opencv-python
然后,您可以运行代码:
import cv2
import pygame
cap = cv2.VideoCapture('video.mp4')
success, img = cap.read()
shape = img.shape[1::-1]
wn = pygame.display.set_mode(shape)
clock = pygame.time.Clock()
while success:
clock.tick(60)
success, img = cap.read()
for event in pygame.event.get():
if event.type == pygame.QUIT:
success = False
wn.blit(pygame.image.frombuffer(img.tobytes(), shape, "BGR"), (0, 0))
pygame.display.update()
pygame.quit()
解决方案 4:
这是另一种方法。利用方便的ffmpeg-python包装器来利用ffmpeg。
import ffmpeg
import pygame
import sys
import numpy as np
input_file = "input.mp4"
probe = ffmpeg.probe(input_file)
video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
width = int(video_info['width'])
height = int(video_info['height'])
process = (
ffmpeg
.input(input_file)
.output("pipe:", format="rawvideo", pix_fmt="rgb24")
.run_async(pipe_stdout=True)
)
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
in_bytes = process.stdout.read(width * height * 3)
if not in_bytes:
break
in_frame = (
np.frombuffer(in_bytes, dtype="uint8")
.reshape([height, width, 3])
)
out_frame = pygame.surfarray.make_surface(np.transpose(in_frame, (1, 0, 2)))
screen.blit(out_frame, (0, 0))
pygame.display.flip()
clock.tick(60)
process.wait()
pygame.quit()
解决方案 5:
实际上有一种方法可以做到这一点moviepy
。这是一个在 pygame 表面显示视频的演示:
import pygame
from moviepy.editor import VideoFileClip
# Initialize Pygame
pygame.init()
# Load the video clip
clip = VideoFileClip("video.mp4") # (or .webm, .avi, etc.)
def getSurface(t, srf=None):
frame = clip.get_frame(t=t) # t is the time in seconds
if srf is None:
# Transpose the array and create the Pygame surface
return pygame.surfarray.make_surface(frame.swapaxes(0, 1))
else:
pygame.surfarray.blit_array(srf, frame.swapaxes(0, 1))
return srf
surface = getSurface(0)
screen = pygame.display.set_mode(surface.get_size(), 0, 32)
# Run the Pygame loop to keep the window open
running = True
t = 0
while running:
# Draw the surface onto the window
screen.blit(getSurface(t, surface), (0, 0))
pygame.display.flip()
t += 1/60 # use actual fps here
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Quit Pygame
pygame.quit()
您还可以从 moviepy 中提取音频并与视频一起单独播放,但我没有可运行的演示。