ナビゲーション

Python

Python で動画をレンダリングするBeta

Python SDK で、動画テンプレートを MP4 としてレンダリングし、その進行状況を追います。

動画テンプレートは MP4 としてレンダリングされます。動画の 1 秒が 1 回の生成として数えられ、60 fps では 2 回として数えられます。動画のデザイン方法は、動画の生成で説明しています。

render_video と render_and_wait_video は、テンプレート ID とキーワード引数を受け取ります。

#template_idstrrequired

動画テンプレートの ID。たとえば tpl_xxx です。

#modificationslist[dict]

テンプレートのレイヤーに設定する値。動画レイヤーは src を、音声トラックは名前と src を受け取ります。各レイヤーが受け付けるフィールドは、Modifications にあります。

レンダリングして URL を待つ

render_and_wait_video は、{"result": url} または {"error": {...}} を返します。

result = client.render_and_wait_video(
    "tpl_xxx",
    modifications=[
        {"name": "headline", "text": "Summer sale"},
        {"name": "music", "src": "https://example.com/song.mp3"},
    ],
)

if "error" in result:
    raise RuntimeError(result["error"]["message"])

print(result["result"])

進行状況を追う

render_video は、イベントの dict を yield します。最後のイベントは done または error です。

for event in client.render_video("tpl_xxx", modifications=[{"name": "headline", "text": "Summer sale"}]):
    if event["type"] == "queued":
        print(f"{event['ahead']} videos before this one")
    elif event["type"] == "progress":
        print(f"{event['progress']:.0%}")
    elif event["type"] == "done":
        print(event["url"])
    elif event["type"] == "error":
        print(event["error"]["message"])
イベント フィールド
created id: 動画の ID (例: vid_xxx)
queued ahead: この動画より前にある動画の数
progress frame、totalFrames、0 から 1 までの progress
done url: MP4 の URL
error error: code、message、requestId

無効な API キーやクォータの使い切りなどでリクエストが拒否されると、error イベントが 1 つ返ります。動画は数分間順番を待つことがあるため、クライアントのタイムアウトは接続にだけ適用されます。

接続が切れたときに再接続する

接続が切れても、動画は最後までレンダリングされます。そのあと render_video は、created イベントの ID で同じ動画をもう一度読み取り、イベントを yield し続けます。レンダリングのリクエストを再送することはないので、動画 2 本分の料金はかかりません。

試行 試行前の待ち時間
1 1 秒
2 2 秒
3 4 秒
4 8 秒

試行回数を使い切った場合や、created イベントより前に接続が切れた場合は、最後のイベントがコード TIMEOUT_ERROR の error になります。render_and_wait_video も同じように再接続します。

待たずに動画を開始する

create_video は動画を開始し、その ID をすぐに返します。レンダリングの完了は待ちません。そのあと、get_video または watch_video で動画を読み取ります。

result = client.create_video("tpl_xxxxxxxxx", modifications=[{"name": "title", "text": "Hi"}])

if "error" in result:
    raise RuntimeError(result["error"]["message"])

print(result["result"]["id"])  # vid_xxx, with the status queued

create_video がレンダリングを送信するのは 1 回だけです。もう一度リクエストすると、2 本目の動画がレンダリングされます。

動画をもう一度読み取る

created イベントの ID を保存しておいてください。get_video は、動画のステータスを返し、完了していれば URL も返します。

result = client.get_video("vid_xxx")

if "error" in result:
    raise RuntimeError(result["error"]["message"])

video = result["result"]
print(video["status"], video.get("url"))

status は queued、rendering、done、failed のいずれかです。失敗した動画には error の文字列があります。未知の ID を指定すると、コード NOT_FOUND のエラーになります。

watch_video は、動画の最新のイベントから、もう一度イベントを yield します。created イベントはなく、render_video と同じように再接続します。

for event in client.watch_video("vid_xxx"):
    if event["type"] == "done":
        print(event["url"])