PHP
PHP で動画をレンダリングするBeta
PHP SDK で、動画テンプレートを MP4 としてレンダリングし、その進行状況を追います。
動画テンプレートは MP4 としてレンダリングされます。動画の 1 秒が 1 回の生成として数えられ、60 fps では 2 回として数えられます。動画のデザイン方法は、動画の生成で説明しています。
renderVideo と renderAndWaitVideo は、テンプレート ID とオプションの配列を受け取ります。
動画テンプレートの ID。たとえば tpl_xxx です。
テンプレートのレイヤーに設定する値。動画レイヤーは src を、音声トラックは名前と src を受け取ります。各レイヤーが受け付けるフィールドは、Modifications にあります。
レンダリングして URL を待つ
renderAndWaitVideo は、['result' => $url] または ['error' => [...]] を返します。
$result = $client->renderAndWaitVideo('tpl_xxx', [
'modifications' => [
['name' => 'headline', 'text' => 'Summer sale'],
['name' => 'music', 'src' => 'https://example.com/song.mp3'],
],
]);
if (isset($result['error'])) {
throw new RuntimeException($result['error']['message']);
}
echo $result['result'];
進行状況を追う
renderVideo は、イベント配列の Generator を返します。最後のイベントは done または error です。
foreach ($client->renderVideo('tpl_xxx', ['modifications' => [['name' => 'headline', 'text' => 'Summer sale']]]) as $event) {
match ($event['type']) {
'created' => printf("Video %s\n", $event['id']),
'queued' => printf("%d videos before this one\n", $event['ahead']),
'progress' => printf("%d%%\n", $event['progress'] * 100),
'done' => print($event['url'] . "\n"),
'error' => print($event['error']['message'] . "\n"),
};
}
| イベント | フィールド |
|---|---|
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 つ返ります。動画は数分間順番を待つことがあるため、クライアントのタイムアウトは接続にだけ適用されます。
接続が切れたときに再接続する
接続が切れても、動画は最後までレンダリングされます。そのあと renderVideo は、created イベントの ID で同じ動画をもう一度読み取り、イベントを返し続けます。レンダリングのリクエストを再送することはないので、動画 2 本分の料金はかかりません。
| 試行 | 試行前の待ち時間 |
|---|---|
| 1 | 1 秒 |
| 2 | 2 秒 |
| 3 | 4 秒 |
| 4 | 8 秒 |
試行回数を使い切った場合や、created イベントより前に接続が切れた場合は、最後のイベントがコード TIMEOUT_ERROR の error になります。renderAndWaitVideo も同じように再接続します。
待たずに動画を開始する
createVideo は動画を開始し、その ID をすぐに返します。レンダリングの完了は待ちません。そのあと、getVideo または watchVideo で動画を読み取ります。
$result = $client->createVideo('tpl_xxxxxxxxx', [['name' => 'title', 'text' => 'Hi']]);
if (isset($result['error'])) {
throw new RuntimeException($result['error']['message']);
}
echo $result['result']['id']; // vid_xxx, with the status queued
createVideo がレンダリングを送信するのは 1 回だけです。もう一度リクエストすると、2 本目の動画がレンダリングされます。
動画をもう一度読み取る
created イベントの ID を保存しておいてください。getVideo は、動画のステータスを返し、完了していれば URL も返します。
$result = $client->getVideo('vid_xxx');
if (isset($result['error'])) {
throw new RuntimeException($result['error']['message']);
}
echo $result['result']['status'] . ' ' . ($result['result']['url'] ?? '');
status は queued、rendering、done、failed のいずれかです。失敗した動画には error の文字列があります。未知の ID を指定すると、コード NOT_FOUND のエラーになります。
watchVideo は、動画の最新のイベントから、もう一度イベントを返します。created イベントはなく、renderVideo と同じように再接続します。
foreach ($client->watchVideo('vid_xxx') as $event) {
if ($event['type'] === 'done') {
echo $event['url'] . "\n";
}
}