Anton's answer đã truyền cảm hứng cho tôi để tìm hiểu kỹ hơn về câu hỏi này. Hạnh phúc, tôi phát hiện ra nó có thể run Pygame headlessly, cho phép tôi hoàn thành những gì tôi muốn làm một chút đơn giản hơn phương pháp của Anton.
Các công việc cơ bản diễn ra như sau:
- Cài đặt pygame để chạy headlessly
- Chạy trò chơi của tôi, tiết kiệm một hình ảnh màn hình cho mỗi khung sử dụng Pygame
- Tạo video từ các tập tin hình ảnh sử dụng ffmpeg
- Tải video lên Youtube bằng cách sử dụng youtube-upload
Mẫu mã (phiên bản đơn giản của mã riêng của tôi vì vậy điều này đã không được kiểm tra nghiêm ngặt):
# 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)
Bạn có thể muốn xóa tất cả các file ảnh sau khi video của bạn được tạo.
Tôi đã có một chút rắc rối chụp ảnh chụp màn hình headlessly, mà tôi làm việc xung quanh như đã mô tả ở đây: In Pygame, how can I save a screen image in headless mode?
tôi đã có thể sắp xếp kịch bản của tôi để chạy như một cronjob mà không vấn đề.
Vui mừng được trợ giúp và hy vọng phương pháp bạn mô tả hoạt động tốt. Tùy thuộc vào thời gian chụp, tôi sẽ quan tâm đến tất cả dung lượng đĩa cần thiết để chụp ảnh và CPU cần chuyển đổi chúng thành video (mã hóa phiên Xvfb sẽ rẻ hơn vì nó không cần png giải mã từng khung hình). Xvfb/ffmpeg với lý thuyết sẽ ít thuế hơn. –