アントンの答えは、この質問をより深く掘り下げるきっかけになりました。幸いなことに、 Pygame を headless で実行できることを発見したので、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)
ビデオが作成されたら、おそらくすべての画像ファイルを削除したいと思うでしょう。
スクリーンショットをヘッドレスでキャプチャするのに少し問題がありましたが、ここで説明するように回避しました: In Pygame, how can I save a screen image in headless mode?
問題なく、スクリプトを cronjob として実行するようにスケジュールできました。