Anton 的回答激发了我对这个问题的深入挖掘。令人高兴的是,我发现可以无头运行 Pygame,使我能够比 Anton 的方法更简单地完成我想做的事情。
基本工作流程如下:
- 设置 pygame 以无头运行
- 运行我的游戏,使用Pygame为每一帧保存一个屏幕图像
- 使用ffmpeg从图像文件创建视频
- 使用youtube-upload 将视频上传到 Youtube
示例代码(我自己的代码的简化版本,因此尚未经过严格测试):
# imports
import os
import subprocess
import pygame
import mygame
# setup pygame to run headlessly
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.display.set_mode((1,1))
# can't use display surface to capture images for some reason, so I set up
# my own screen using a pygame rect
width, height = 400, 400
black = (0,0,0)
flags = pygame.SRCALPHA
depth = 32
screen = pygame.Surface((width, height), flags, depth)
pygame.draw.rect(screen, black, (0, 0, width, height), 0)
# my game object: screen becomes attribute of game object: game.screen
game = mygame.MyGame(screen)
# need this file format for saving images and encoding video with ffmpeg
image_file_f = 'frame_%03d.png'
# run game, saving images of each screen
game.init()
while game.is_running:
game.update() # updates screen
image_path = image_file_f % (game.frame_num)
pygame.image.save(game.screen, image_path)
# create video of images using ffmpeg
output_path = '/tmp/mygame_clip_for_youtube.mp4'
ffmpeg_command = (
'ffmpeg',
'-r', str(game.fps),
'-sameq',
'-y',
'-i', image_file_f,
output_path
)
subprocess.check_call(ffmpeg_command)
print "video file created:", output_path
# upload video to Youtube using youtube-upload
gmail_address='your.name@gmail.com'
gmail_password='test123'
upload_command = (
'youtube-upload',
'--unlisted',
'--email=%s' % (gmail_address),
'--password=%s' % (gmail_password),
'--title="Sample Game Clip"',
'--description="See https://stackoverflow.com/q/14450581/1093087"',
'--category=Games',
output_path
)
proc = subprocess.Popen(
upload_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate()
print "youtube link: %s" % (out)
创建视频后,您可能希望删除所有图像文件。
我确实在无头捕获屏幕截图时遇到了一点麻烦,我按照这里的描述解决了这个问题:在 Pygame 中,如何以无头模式保存屏幕图像?
我能够安排我的脚本作为 cronjob 运行而没有问题。