Anton's answer啓發我深入挖掘這個問題。令人高興的是,我發現有可能到run Pygame headlessly,使我能夠比安東的方法更簡單地完成我想要做的事情。
的基本工作流程去如下:
- 安裝pygame的運行headlessly
- 運行我的遊戲,節省了屏幕圖像使用ffmpeg
使用
Pygame
- 創建從圖像文件視頻每一幀
- 使用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='[email protected]'
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)
你可能會想,一旦您的視頻創建,刪除所有圖像文件。
我有一個小麻煩捕捉截圖headlessly,這是我工作圍繞如下所述:In Pygame, how can I save a screen image in headless mode?
我可以安排我的腳本爲沒有問題的cronjob運行。
很高興爲您提供幫助,希望您介紹的方法運作良好。根據捕獲的時間長短,我會擔心捕獲圖像所需的所有磁盤空間,並且CPU需要將它們轉換爲視頻(編碼Xvfb會話應該更便宜,因爲它不需要png解碼每一幀)。理論上Xvfb/ffmpeg在一起會減少徵稅。 –