在 VOD 素材资源中插入广告

本页介绍了如何使用 Video Stitcher API 和 curl、PowerShell 或客户端库将广告插入视频点播 (VOD) 资产的播放中。

准备工作

在调用 Video Stitcher API 之前,请完成以下步骤:

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.
  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  5. Make sure that billing is enabled for your Google Cloud project.

  6. Enable the Video Stitcher API:

    gcloud services enable videostitcher.googleapis.com
  7. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

  8. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/videostitcher.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  9. Install the Google Cloud CLI.
  10. To initialize the gcloud CLI, run the following command:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Make sure that billing is enabled for your Google Cloud project.

  13. Enable the Video Stitcher API:

    gcloud services enable videostitcher.googleapis.com
  14. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

  15. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/videostitcher.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  16. 本快速入门需要 MPEG-DASH 清单 (MPD) 文件或 HTTP Live Streaming (HLS) 清单 (M3U8) 文件以及关联的片段文件。您可以使用现有的 VOD 文件,也可以使用 Transcoder API 创建 VOD 源文件
  17. 您可以选择在本快速入门中使用内容分发网络 (CDN)。如果您尚未配置 CDN,请按照媒体 CDN 快速入门中的步骤操作,并进行以下修改:
    1. 上传 MPEG-DASH 或 HLS 清单文件 复制到 Cloud Storage 存储桶中。
    2. 您无需将 Cloud Storage 存储桶设为可公开读取。
    3. 您可以使用签名网址或未签名网址。

创建 CDN 密钥

Video Stitcher API 可以从内容分发网络 (CDN) 提取视频。如果视频资产受网址签名保护,则必须向 Video Stitcher API 注册 CDN 密钥。

要注册 CDN 密钥,请使用 projects.locations.cdnKeys.create 方法。

REST(媒体 CDN)

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号; 该名称位于 IAM 设置页面的项目编号字段中
  • LOCATION:要在其中创建 CDN 的位置 key;请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 的用户定义标识符 密钥,该密钥将成为 CDN 密钥资源名称的最后一个组成部分。 此 ID 只能包含小写字母、数字和连字符。第一个字符必须是字母,最后一个字符必须是字母或数字,并且 每个 ID 最多包含 63 个字符。
  • HOSTNAME:要关联的 CDN 的主机名 此 CDN 密钥(例如,35.190.60.252 这样的 IP 地址或域名 cdn.example.com)
  • MEDIA_CDN_KEYNAME媒体 CDN 密钥的密钥集名称
  • MEDIA_CDN_PRIVATE_KEY:64 字节的 Ed25519 私钥(采用 base64 编码的字符串)。请参阅 为媒体 CDN 创建私钥 用于 。

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
此命令会创建一个 长时间运行的操作 (LRO) 您可以查询该 ID 以跟踪进度。复制返回的 OPERATION_ID, 它是 name 字段的最后一部分,将在下一部分中使用。

REST (Cloud CDN)

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:创建 CDN 密钥的位置;请使用某个受支持的区域
    显示位置
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 的用户定义标识符 密钥,该密钥将成为 CDN 密钥资源名称的最后一个组成部分。 此 ID 只能包含小写字母、数字和连字符。第一个字符必须是字母,最后一个字符必须是字母或数字,并且 每个 ID 最多包含 63 个字符。
  • HOSTNAME:要与此 CDN 密钥关联的 CDN 的主机名(例如 IP 地址,如 35.190.60.252,或域名,如 cdn.example.com
  • GCDN_KEYNAMECloud CDN 密钥
  • GCDN_PRIVATE_KEY:base64 编码的字符串 Cloud CDN 密钥的 Secret

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
此命令会创建一个长时间运行的操作 (LRO),您可以对其进行查询以跟踪进度。复制返回的 OPERATION_ID, 它是 name 字段的最后一部分,将在下一部分中使用。

REST(Akamai CDN)

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:要在其中创建 CDN 的位置 key;请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 的用户定义标识符 密钥,该密钥将成为 CDN 密钥资源名称的最后一个组成部分。 此 ID 只能包含小写字母、数字和连字符。第一个字符必须是字母,最后一个字符必须是字母或数字,并且 每个 ID 最多包含 63 个字符。
  • HOSTNAME:要与此 CDN 密钥关联的 CDN 的主机名(例如 IP 地址,如 35.190.60.252,或域名,如 cdn.example.com
  • AKAMAI_TOKEN_KEY:Akamai CDN 边缘配置的 base64 编码字符串令牌键

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
此命令会创建一个长时间运行的操作 (LRO),您可以对其进行查询以跟踪进度。复制返回的 OPERATION_ID, 它是 name 字段的最后一部分,将在下一部分中使用。

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 有关详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf;
using System.Threading.Tasks;

public class CreateCdnKeySample
{
    public async Task<CdnKey> CreateCdnKeyAsync(
    string projectId, string location, string cdnKeyId, string hostname,
    string keyName, string privateKey, bool isMediaCdn)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            Hostname = hostname
        };

        if (isMediaCdn)
        {
            cdnKey.MediaCdnKey = new MediaCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }
        else
        {
            cdnKey.GoogleCdnKey = new GoogleCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }

        CreateCdnKeyRequest request = new CreateCdnKeyRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            CdnKeyId = cdnKeyId,
            CdnKey = cdnKey
        };

        // Make the request.
        Operation<CdnKey, OperationMetadata> response = await client.CreateCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<CdnKey, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createCDNKey creates a CDN key. A CDN key is used to retrieve protected media.
// If isMediaCDN is true, create a Media CDN key. If false, create a Cloud
// CDN key. To create a privateKey value for Media CDN, see
// https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
func createCDNKey(w io.Writer, projectID, keyID, privateKey string, isMediaCDN bool) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// privateKey := "my-private-key"
	// isMediaCDN := true
	location := "us-central1"
	hostname := "cdn.example.com"
	keyName := "cdn-key"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	var req *stitcherstreampb.CreateCdnKeyRequest
	if isMediaCDN {
		req = &stitcherstreampb.CreateCdnKeyRequest{
			Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
			CdnKeyId: keyID,
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_MediaCdnKey{
					MediaCdnKey: &stitcherstreampb.MediaCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Hostname: hostname,
			},
		}
	} else {
		req = &stitcherstreampb.CreateCdnKeyRequest{
			Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
			CdnKeyId: keyID,
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_GoogleCdnKey{
					GoogleCdnKey: &stitcherstreampb.GoogleCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Hostname: hostname,
			},
		}
	}

	// Creates the CDN key.
	op, err := client.CreateCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateCdnKey: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "CDN key: %v", response.GetName())
	return nil
}

Java

在尝试此示例之前,请按照Java Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CreateCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.GoogleCdnKey;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.MediaCdnKey;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateCdnKey {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";
    String hostname = "cdn.example.com";
    String keyName = "my-key";
    // To create a privateKey value for Media CDN, see
    // https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
    String privateKey = "my-private-key"; // will be converted to a byte string
    Boolean isMediaCdn = true;

    createCdnKey(projectId, location, cdnKeyId, hostname, keyName, privateKey, isMediaCdn);
  }

  // createCdnKey creates a Media CDN key or a Cloud CDN key. A CDN key is used to retrieve
  // protected media.
  public static CdnKey createCdnKey(
      String projectId,
      String location,
      String cdnKeyId,
      String hostname,
      String keyName,
      String privateKey,
      Boolean isMediaCdn)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CdnKey cdnKey;
      if (isMediaCdn) {
        cdnKey =
            CdnKey.newBuilder()
                .setHostname(hostname)
                .setMediaCdnKey(
                    MediaCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      } else {
        cdnKey =
            CdnKey.newBuilder()
                .setHostname(hostname)
                .setGoogleCdnKey(
                    GoogleCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      }

      CreateCdnKeyRequest createCdnKeyRequest =
          CreateCdnKeyRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setCdnKeyId(cdnKeyId)
              .setCdnKey(cdnKey)
              .build();

      CdnKey result =
          videoStitcherServiceClient
              .createCdnKeyAsync(createCdnKeyRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Created new CDN key: " + result.getName());
      return result;
    }
  }
}

Node.js

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const location = 'us-central1';
const hostname = 'cdn.example.com';
const keyName = 'cdn-key';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// privateKey = 'my-private-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createCdnKey() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    cdnKey: {
      hostname: hostname,
    },
    cdnKeyId: cdnKeyId,
  };

  if (isMediaCdn === 'true') {
    request.cdnKey.mediaCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
  } else {
    request.cdnKey.googleCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
  }

  const [operation] = await stitcherClient.createCdnKey(request);
  const [response] = await operation.promise();
  console.log(`CDN key: ${response.name}`);
}

createCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在尝试此示例之前,请按照PHP Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateCdnKeyRequest;
use Google\Cloud\Video\Stitcher\V1\GoogleCdnKey;
use Google\Cloud\Video\Stitcher\V1\MediaCdnKey;

/**
 * Creates a CDN key. Cloud CDN keys and Media CDN keys are supported.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the CDN key
 * @param string  $cdnKeyId           The ID of the CDN key to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $keyName            For a Media CDN key, this is the keyset name.
 *                                    For a Cloud CDN key, this is the public name of the
 *                                    CDN key.
 * @param string  $privateKey         For a Media CDN key, this is a 64-byte Ed25519 private
 *                                    key encoded as a base64-encoded string. See
 *                                    https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
 *                                    for more information. For a Cloud CDN key,
 *                                    this is a base64-encoded string secret.
 * @param bool    $isMediaCdn         If true, create a Media CDN key. If false,
 *                                    create a Cloud CDN key.
 */
function create_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $keyName,
    string $privateKey,
    bool $isMediaCdn
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $cdnKey = new CdnKey();
    $cdnKey->setHostname($hostname);

    if ($isMediaCdn == true) {
        $cloudCdn = new MediaCdnKey();
        $cdnKey->setMediaCdnKey($cloudCdn);
    } else {
        $cloudCdn = new GoogleCdnKey();
        $cdnKey->setGoogleCdnKey($cloudCdn);
    }
    $cloudCdn->setKeyName($keyName);
    $cloudCdn->setPrivateKey($privateKey);

    // Run CDN key creation request
    $request = (new CreateCdnKeyRequest())
        ->setParent($parent)
        ->setCdnKey($cdnKey)
        ->setCdnKeyId($cdnKeyId);
    $operationResponse = $stitcherClient->createCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('CDN key: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def create_cdn_key(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    key_name: str,
    private_key: str,
    is_cloud_cdn: bool,
) -> stitcher_v1.types.CdnKey:
    """Creates a Cloud CDN or Media CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the CDN key.
        cdn_key_id: The user-defined CDN key ID.
        hostname: The hostname to which this CDN key applies.
        key_name: For a Media CDN key, this is the keyset name.
                  For a Cloud CDN key, this is the public name of the CDN key.
        private_key: For a Media CDN key, this is a 64-byte Ed25519 private
                     key encoded as a base64-encoded string.
                     See https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
                     for more information. For a Cloud CDN key, this is a base64-encoded string secret.
        is_cloud_cdn: If true, create a Cloud CDN key. If false, create a Media CDN key.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    cdn_key = stitcher_v1.types.CdnKey(
        name=cdn_key_id,
        hostname=hostname,
    )

    if is_cloud_cdn:
        cdn_key.google_cdn_key = stitcher_v1.types.GoogleCdnKey(
            key_name=key_name,
            private_key=private_key,
        )
    else:
        cdn_key.media_cdn_key = stitcher_v1.types.MediaCdnKey(
            key_name=key_name,
            private_key=private_key,
        )

    operation = client.create_cdn_key(
        parent=parent, cdn_key_id=cdn_key_id, cdn_key=cdn_key
    )
    response = operation.result()
    print(f"CDN key: {response.name}")
    return response

Ruby

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Create a Media CDN or Cloud CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] The user-defined CDN key ID
# @param hostname [String] The hostname to which this CDN key applies
# @param key_name [String] For a Media CDN key, this is the keyset name.
#   For a Cloud CDN key, this is the public name of the CDN key.
# @param private_key [String] For a Media CDN key, this is a 64-byte Ed25519
#   private key encoded as a base64-encoded string. See
#   https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
#   for more information. For a Cloud CDN key, this is a base64-encoded string
#   secret.
# @param is_media_cdn [Boolean] If true, create a Media CDN key. If false,
#  create a Cloud CDN key.
#
def create_cdn_key project_id:, location:, cdn_key_id:, hostname:, key_name:,
                   private_key:, is_media_cdn:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location
  # Build the path for the CDN key resource.
  cdn_key_path = client.cdn_key_path project: project_id, location: location,
                                     cdn_key: cdn_key_id

  # Set the CDN key fields.
  new_cdn_key = if is_media_cdn
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    media_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                else
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    google_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                end

  operation = client.create_cdn_key parent: parent, cdn_key: new_cdn_key,
                                    cdn_key_id: cdn_key_id

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the CDN key name.
  puts "CDN key: #{operation.response.name}"
end

查看结果

如需检查是否已创建 CDN 密钥,请使用 projects.locations.operations.get 方法。如果响应中包含 "done: false",请重复该命令,直到出现 响应包含 "done: true"

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:数据的位置; 请使用某个受支持的区域
    显示位置
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • OPERATION_ID:操作的标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "endTime": END_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.video.stitcher.v1.CdnKey",
    "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "hostname": "HOSTNAME",
    "mediaCdnKey": {
      "keyName": "MEDIA_CDN_KEYNAME"
    }
  }
}

创建 VOD 配置

在创建 VOD 会话之前,您需要为其创建配置。许多 VOD 会话可以共享相同的配置。

如需创建配置,请使用 projects.locations.vodConfigs.create 方法。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:创建视频点播配置的位置;请使用某个受支持的区域
    显示位置
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_CONFIG_ID:VOD 配置的用户定义标识符。 此 ID 只能包含小写字母、数字和连字符。 第一个字符必须是字母,最后一个字符必须是字母或数字,并且 每个 ID 最多包含 63 个字符。
  • VOD_URI:要拼接的媒体的 URI。这个 URI 必须引用 MPEG-DASH 清单 (MPD) 文件或 HLS 清单 (M3U8) 文件。使用 公开 URI 或 注册了 CDN 密钥
  • AD_TAG_URI
    广告代码的公开 URI;如果你 如果还没有的话,可以使用 VMAP 前贴片广告 示例

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/vodConfigs/VOD_CONFIG_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
此命令会创建一个 长时间运行的操作 (LRO) 您可以查询该 ID 以跟踪进度。如需了解详情,请参阅检查结果

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 有关详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using System.Threading.Tasks;

public class CreateVodConfigSample
{
    public async Task<VodConfig> CreateVodConfigAsync(
        string projectId, string location, string vodConfigId, string sourceUri, string adTagUri)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateVodConfigRequest request = new CreateVodConfigRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            VodConfigId = vodConfigId,
            VodConfig = new VodConfig
            {
                SourceUri = sourceUri,
                AdTagUri = adTagUri
            }
        };

        // Make the request.
        Operation<VodConfig, OperationMetadata> response = await client.CreateVodConfigAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<VodConfig, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

在尝试此示例之前,请按照Go Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createVodConfig creates a VOD config. VOD configs are used to configure VOD sessions.
func createVodConfig(w io.Writer, projectID, vodConfigID, sourceURI string) error {
	// projectID := "my-project-id"
	// vodConfigID := "my-vod-config-id"

	// Uri of the media to stitch; this URI must reference either an MPEG-DASH
	// manifest (.mpd) file or an M3U playlist manifest (.m3u8) file.
	// sourceURI := "https://storage.googleapis.com/my-bucket/main.mpd"

	// See https://cloud.google.com/video-stitcher/docs/concepts for information
	// on ad tags and ad metadata. This sample uses an ad tag URL that displays
	// a VMAP Pre-roll ad
	// (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags).
	adTagURI := "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator="
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.CreateVodConfigRequest{
		Parent:      fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		VodConfigId: vodConfigID,
		VodConfig: &stitcherstreampb.VodConfig{
			SourceUri: sourceURI,
			AdTagUri:  adTagURI,
		},
	}
	// Creates the VOD config.
	op, err := client.CreateVodConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateVodConfig: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "VOD config: %v", response.GetName())
	return nil
}

Java

在尝试此示例之前,请按照Java Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.CreateVodConfigRequest;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodConfig;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateVodConfig {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String vodConfigId = "my-vod-config-id";
    // URI of the VOD stream to stitch; this URI must reference either an MPEG-DASH
    // manifest (.mpd) file or an M3U playlist manifest (.m3u8) file.
    String sourceUri = "https://storage.googleapis.com/my-bucket/main.mpd";
    // See VMAP Pre-roll
    // (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags)
    String adTagUri = "https://pubads.g.doubleclick.net/gampad/ads...";

    createVodConfig(projectId, location, vodConfigId, sourceUri, adTagUri);
  }

  // Creates a video on demand (VOD) config. VOD configs are used to configure VOD
  // sessions. For more information, see
  // https://cloud.google.com/video-stitcher/docs/how-to/managing-vod-configs.
  public static VodConfig createVodConfig(
      String projectId, String location, String vodConfigId, String sourceUri, String adTagUri)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CreateVodConfigRequest createVodConfigRequest =
          CreateVodConfigRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setVodConfigId(vodConfigId)
              .setVodConfig(
                  VodConfig.newBuilder().setSourceUri(sourceUri).setAdTagUri(adTagUri).build())
              .build();

      VodConfig response =
          videoStitcherServiceClient
              .createVodConfigAsync(createVodConfigRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Created new VOD config: " + response.getName());
      return response;
    }
  }
}

Node.js

在尝试此示例之前,请按照Node.js Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// vodConfigId = 'my-vod-config-id';
// sourceUri = 'https://storage.googleapis.com/my-bucket/main.mpd';
// See VMAP Pre-roll
// (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags)
// adTagUri = 'https://pubads.g.doubleclick.net/gampad/ads...';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createVodConfig() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    vodConfig: {
      sourceUri: sourceUri,
      adTagUri: adTagUri,
    },
    vodConfigId: vodConfigId,
  };
  const [operation] = await stitcherClient.createVodConfig(request);
  const [response] = await operation.promise();
  console.log(`response.name: ${response.name}`);
}

createVodConfig().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在尝试此示例之前,请按照PHP Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateVodConfigRequest;
use Google\Cloud\Video\Stitcher\V1\VodConfig;

/**
 * Creates a VOD config. VOD configs are used to configure VOD sessions.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the VOD config
 * @param string $vodConfigId          The name of the VOD config to be created
 * @param string $sourceUri            Uri of the media to stitch; this URI must
 *                                     reference either an MPEG-DASH manifest
 *                                     (.mpd) file or an M3U playlist manifest
 *                                     (.m3u8) file.
 * @param string $adTagUri             The Uri of the ad tag
 */
function create_vod_config(
    string $callingProjectId,
    string $location,
    string $vodConfigId,
    string $sourceUri,
    string $adTagUri
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);

    $vodConfig = (new VodConfig())
        ->setSourceUri($sourceUri)
        ->setAdTagUri($adTagUri);

    // Run VOD config creation request
    $request = (new CreateVodConfigRequest())
        ->setParent($parent)
        ->setVodConfigId($vodConfigId)
        ->setVodConfig($vodConfig);
    $operationResponse = $stitcherClient->createVodConfig($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('VOD config: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def create_vod_config(
    project_id: str,
    location: str,
    vod_config_id: str,
    vod_uri: str,
    ad_tag_uri: str,
) -> stitcher_v1.types.VodConfig:
    """Creates a VOD config.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the VOD config.
        vod_config_id: The user-defined VOD config ID.
        vod_uri: URI of the VOD to stitch; this URI must reference either an
                    MPEG-DASH manifest (.mpd) file or an M3U playlist manifest
                    (.m3u8) file.
        ad_tag_uri: Uri of the ad tag.

    Returns:
        The VOD config resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    vod_config = stitcher_v1.types.VodConfig(
        source_uri=vod_uri,
        ad_tag_uri=ad_tag_uri,
    )

    operation = client.create_vod_config(
        parent=parent, vod_config_id=vod_config_id, vod_config=vod_config
    )
    response = operation.result()
    print(f"VOD config: {response.name}")
    return response

Ruby

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Create a VOD config. VOD configs are used to create VOD sessions.
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param vod_config_id [String] Your VOD config name (e.g. `my-vod-config`)
# @param source_uri [String] Uri of the VOD stream to stitch
#   (e.g. `https://storage.googleapis.com/my-bucket/main.mpd`)
# @param ad_tag_uri [String] Uri of the ad tag
#   (e.g. `https://pubads.g.doubleclick.net/gampad/ads...`)
#
def create_vod_config project_id:, location:, vod_config_id:, source_uri:,
                      ad_tag_uri:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  # Set the VOD config fields.
  new_vod_config = {
    source_uri: source_uri,
    ad_tag_uri: ad_tag_uri
  }

  operation = client.create_vod_config parent: parent,
                                       vod_config_id: vod_config_id,
                                       vod_config: new_vod_config

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the VOD config name.
  puts "VOD config: #{operation.response.name}"
end

获取配置

如需获取配置,请使用 projects.locations.vodConfigs.get 方法。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:VOD 配置的位置; 请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_CONFIG_ID:用户定义的标识符 VOD 配置

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodConfigs/VOD_CONFIG_ID",
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "state": "READY"
}

C#

在尝试此示例之前,请按照C# Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Video.Stitcher.V1;

public class GetVodConfigSample
{
    public VodConfig GetVodConfig(
        string projectId, string location, string vodConfigId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetVodConfigRequest request = new GetVodConfigRequest
        {
            VodConfigName = VodConfigName.FromProjectLocationVodConfig(projectId, location, vodConfigId)
        };

        // Call the API.
        VodConfig response = client.GetVodConfig(request);

        // Return the result.
        return response;
    }
}

Go

在尝试此示例之前,请按照Go Video Stitcher API 快速入门:使用 客户端库。 有关详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// getVodConfig gets a previously-created VOD config.
func getVodConfig(w io.Writer, projectID, vodConfigID string) error {
	// projectID := "my-project-id"
	// vodConfigID := "my-vod-config-id"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.GetVodConfigRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/vodConfigs/%s", projectID, location, vodConfigID),
	}

	response, err := client.GetVodConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetVodConfig: %w", err)
	}
	b, err := json.MarshalIndent(response, "", " ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}

	fmt.Fprintf(w, "VOD config:\n%s", string(b))
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.GetVodConfigRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodConfig;
import com.google.cloud.video.stitcher.v1.VodConfigName;
import java.io.IOException;

public class GetVodConfig {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String vodConfigId = "my-vod-config-id";

    getVodConfig(projectId, location, vodConfigId);
  }

  // Gets a video on demand (VOD) config.
  public static VodConfig getVodConfig(String projectId, String location, String vodConfigId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      GetVodConfigRequest getVodConfigRequest =
          GetVodConfigRequest.newBuilder()
              .setName(VodConfigName.of(projectId, location, vodConfigId).toString())
              .build();

      VodConfig response = videoStitcherServiceClient.getVodConfig(getVodConfigRequest);
      System.out.println("VOD config: " + response.getName());
      return response;
    }
  }
}

Node.js

在尝试此示例之前,请按照Node.js Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// vodConfigId = 'my-vod-config-id';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function getVodConfig() {
  // Construct request
  const request = {
    name: stitcherClient.vodConfigPath(projectId, location, vodConfigId),
  };
  const [vodConfig] = await stitcherClient.getVodConfig(request);
  console.log(`VOD config: ${vodConfig.name}`);
}

getVodConfig().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在尝试此示例之前,请按照PHP Video Stitcher API 快速入门:使用 客户端库。 有关详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\GetVodConfigRequest;

/**
 * Gets a VOD config.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the VOD config
 * @param string $vodConfigId         The ID of the VOD config
 */
function get_vod_config(
    string $callingProjectId,
    string $location,
    string $vodConfigId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->vodConfigName($callingProjectId, $location, $vodConfigId);
    $request = (new GetVodConfigRequest())
        ->setName($formattedName);
    $vodConfig = $stitcherClient->getVodConfig($request);

    // Print results
    printf('VOD config: %s' . PHP_EOL, $vodConfig->getName());
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def get_vod_config(
    project_id: str, location: str, vod_config_id: str
) -> stitcher_v1.types.VodConfig:
    """Gets a VOD config.
    Args:
        project_id: The GCP project ID.
        location: The location of the VOD config.
        vod_config_id: The user-defined VOD config ID.

    Returns:
        The VOD config resource.
    """

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/vodConfigs/{vod_config_id}"
    response = client.get_vod_config(name=name)
    print(f"VOD config: {response.name}")
    return response

Ruby

在尝试此示例之前,请按照Ruby Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Get a VOD config
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param vod_config_id [String] Your VOD config name (e.g. `my-vod-config`)
#
def get_vod_config project_id:, location:, vod_config_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the VOD config.
  name = client.vod_config_path project: project_id, location: location,
                                vod_config: vod_config_id

  # Get the VOD config.
  vod_config = client.get_vod_config name: name

  # Print the vod config name.
  puts "VOD config: #{vod_config.name}"
end

检查状态是否设置为 READY。如果没有,请等待几秒钟,然后发送 请求。

创建会话

如需为广告插播视频创建会话,请使用 projects.locations.vodSessions.create 方法。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBERIAM 设置页面上的项目编号字段中的 Google Cloud 项目编号
  • LOCATION:要在其中创建 session;请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_CONFIG_ID:VOD 配置的用户定义标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodSessions/SESSION_ID",
  "interstitials": {
    "sessionContent": {
      "duration": "60s"
    }
  },
  "playUri": "PLAY_URI", # This is the ad-stitched VOD URI
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "assetId": "ASSET_ID",
  "adTracking": "SERVER",
  "vodConfig": "projects/PROJECT_NUMBER/locations/LOCATION/vodConfigs/VOD_CONFIG_ID"
}

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 有关详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;

public class CreateVodSessionSample
{
    public VodSession CreateVodSession(
        string projectId, string location, string vodConfigId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateVodSessionRequest request = new CreateVodSessionRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            VodSession = new VodSession
            {
                VodConfig = VodConfigName.FormatProjectLocationVodConfig(projectId, location, vodConfigId),
                AdTracking = AdTracking.Server
            }
        };

        // Call the API.
        VodSession session = client.CreateVodSession(request);

        // Return the result.
        return session;
    }
}

Go

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createVodSession creates a video on demand (VOD) session in which to insert ads.
// VOD sessions are ephemeral resources that expire after a few hours.
func createVodSession(w io.Writer, projectID, vodConfigID string) error {
	// projectID := "my-project-id"
	// vodConfigID := "my-vod-config-id"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.CreateVodSessionRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		VodSession: &stitcherstreampb.VodSession{
			VodConfig:  fmt.Sprintf("projects/%s/locations/%s/vodConfigs/%s", projectID, location, vodConfigID),
			AdTracking: stitcherstreampb.AdTracking_SERVER,
		},
	}
	// Creates the VOD session.
	response, err := client.CreateVodSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateVodSession: %w", err)
	}

	fmt.Fprintf(w, "VOD session: %v", response.GetName())
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.AdTracking;
import com.google.cloud.video.stitcher.v1.CreateVodSessionRequest;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodConfigName;
import com.google.cloud.video.stitcher.v1.VodSession;
import java.io.IOException;

public class CreateVodSession {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String vodConfigId = "my-vod-config-id";

    createVodSession(projectId, location, vodConfigId);
  }

  // Creates a video on demand (VOD) session using the parameters in the designated VOD config.
  // For more information, see
  // https://cloud.google.com/video-stitcher/docs/how-to/creating-vod-sessions.
  public static VodSession createVodSession(String projectId, String location, String vodConfigId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CreateVodSessionRequest createVodSessionRequest =
          CreateVodSessionRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setVodSession(
                  VodSession.newBuilder()
                      .setVodConfig(VodConfigName.format(projectId, location, vodConfigId))
                      .setAdTracking(AdTracking.SERVER)
                      .build())
              .build();

      VodSession response = videoStitcherServiceClient.createVodSession(createVodSessionRequest);
      System.out.println("Created VOD session: " + response.getName());
      return response;
    }
  }
}

Node.js

在尝试此示例之前,请按照Node.js Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// vodConfigId = 'my-vod-config-id';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createVodSession() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    vodSession: {
      vodConfig: stitcherClient.vodConfigPath(
        projectId,
        location,
        vodConfigId
      ),
      adTracking: 'SERVER',
    },
  };
  const [session] = await stitcherClient.createVodSession(request);
  console.log(`VOD session: ${session.name}`);
}

createVodSession().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\AdTracking;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateVodSessionRequest;
use Google\Cloud\Video\Stitcher\V1\VodSession;

/**
 * Creates a VOD session. VOD sessions are ephemeral resources that expire
 * after a few hours.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $vodConfigId          The name of the VOD config to use for the session
 */
function create_vod_session(
    string $callingProjectId,
    string $location,
    string $vodConfigId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $vodConfig = $stitcherClient->vodConfigName($callingProjectId, $location, $vodConfigId);
    $vodSession = new VodSession();
    $vodSession->setVodConfig($vodConfig);
    $vodSession->setAdTracking(AdTracking::SERVER);

    // Run VOD session creation request
    $request = (new CreateVodSessionRequest())
        ->setParent($parent)
        ->setVodSession($vodSession);
    $response = $stitcherClient->createVodSession($request);

    // Print results
    printf('VOD session: %s' . PHP_EOL, $response->getName());
}

Python

在尝试此示例之前,请按照Python Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def create_vod_session(
    project_id: str, location: str, vod_config_id: str
) -> stitcher_v1.types.VodSession:
    """Creates a VOD session. VOD sessions are ephemeral resources that expire
    after a few hours.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the session.
        vod_config_id: The user-defined VOD config ID to use to create the
                        session.

    Returns:
        The VOD session resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    vod_config_name = (
        f"projects/{project_id}/locations/{location}/vodConfigs/{vod_config_id}"
    )

    vod_session = stitcher_v1.types.VodSession(
        vod_config=vod_config_name, ad_tracking="SERVER"
    )

    response = client.create_vod_session(parent=parent, vod_session=vod_session)
    print(f"VOD session: {response.name}")
    return response

Ruby

在尝试此示例之前,请按照Ruby Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Create a video on demand (VOD) session. VOD sessions are ephemeral resources
# that expire after a few hours.
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param vod_config_id [String] The VOD config ID (e.g. `my-vod-config`) to use
#
def create_vod_session project_id:, location:, vod_config_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  # Build the resource name of the VOD config.
  vod_config_name = client.vod_config_path project: project_id,
                                           location: location,
                                           vod_config: vod_config_id

  # Set the session fields.
  new_vod_session = {
    vod_config: vod_config_name,
    ad_tracking: Google::Cloud::Video::Stitcher::V1::AdTracking::SERVER
  }

  response = client.create_vod_session parent: parent,
                                       vod_session: new_vod_session

  # Print the VOD session name.
  puts "VOD session: #{response.name}"
end

Video Stitcher API 会为每个请求生成唯一的会话 ID。会话会在 4 小时后过期。

确认广告已拼接

广告必须先编码,然后才能拼接到 VOD 会话中。

如果您在 vodSessions.create 命令中指定的广告已在之前的会话中编码,Video Stitcher API 会在 JSON 响应中包含 adBreaks 事件。Video Stitcher API 仅查找与您的 Google Cloud 项目关联的会话创建的编码广告。

如果广告尚未编码,JSON 响应中不会包含 adBreaks 事件。如果您收到与 上一部分,等待广告编码并完成 重新运行 vodSessions.create 命令。

编码后的广告成功拼接到会话中后,响应应如下所示:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodSessions/SESSION_ID",
  "interstitials": {
    "adBreaks": [
      {
        "progressEvents": [
          {
            "timeOffset": "0s",
            "events": [
              {
                "type": "IMPRESSION",
                "uri": "https://securepubads.g.doubleclick.net/pcs/view..."
              },
              {
                "type": "START",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              ...
            ]
          },
          ...
        ],
        "ads": [
          {
            "duration": "10s",
            "activityEvents": [
              {
                "type": "ERROR",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              {
                "type": "CLICK_THROUGH",
                "uri": "https://pubads.g.doubleclick.net/pcs/click...",
                "id": "GDFP"
              },
              ...
            ]
          }
        ],
        "endTimeOffset": "10s",
        "startTimeOffset": "0s"
      }
    ],
    "sessionContent": {
      "duration": "70s"
    }
  },
  "playUri": "PLAY_URI",
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "assetId": "ASSET_ID",
  "adTracking": "SERVER",
  "vodConfig": "projects/PROJECT_NUMBER/locations/LOCATION/vodConfigs/VOD_CONFIG_ID"
}

您可以通过引用 响应对象的 playUri 字段。

播放与广告拼接的 VOD 视频流

使用响应对象的 playUri 字段中的 URI 播放广告接缝的 VOD 串流。如需在 Shaka Player 中播放此 VOD 会话,请完成以下步骤:

  1. 导航到 Shaka Player 在线媒体播放器。
  2. 点击顶部导航栏中的自定义内容
  3. 点击 + 按钮。
  4. playUri 字段 (PLAY_URI) 的值粘贴到清单网址框中。

  5. 名称框中输入一个名称。

  6. 点击保存

  7. 点击播放

如果您的视频位于 Cloud Storage 存储桶中,请确保 存储桶是公开的,并且启用了 CORS 存储桶

请观看一个由广告拼接的视频 使用 Transcoder API 示例视频VMAP 前贴片广告 广告代码网址。

清理

为避免因本页面中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的 Google Cloud 项目。

删除 VOD 配置

如需删除 VOD 配置,请执行以下操作:

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号; 该名称位于 IAM 设置页面的项目编号字段中
  • LOCATION:VOD 配置的位置; 请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_CONFIG_ID:用户定义的标识符 VOD 配置

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/vodConfigs/VOD_CONFIG_ID",
    "verb": "delete"
  },
  "done": false
}
此命令会创建一个长时间运行的操作 (LRO),您可以对其进行查询以跟踪进度。如需了解详情,请参阅检查结果

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 有关详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class DeleteVodConfigSample
{
    public async Task DeleteVodConfigAsync(
        string projectId, string location, string vodConfigId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        DeleteVodConfigRequest request = new DeleteVodConfigRequest
        {
            VodConfigName = VodConfigName.FromProjectLocationVodConfig(projectId, location, vodConfigId)
        };

        // Make the request.
        Operation<Empty, OperationMetadata> response = await client.DeleteVodConfigAsync(request);

        // Poll until the returned long-running operation is complete.
        await response.PollUntilCompletedAsync();
    }
}

Go

在尝试此示例之前,请按照Go Video Stitcher API 快速入门:使用 客户端库。 有关详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// deleteVodConfig deletes a previously-created VOD config.
func deleteVodConfig(w io.Writer, projectID, vodConfigID string) error {
	// projectID := "my-project-id"
	// vodConfigID := "my-vod-config-id"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.DeleteVodConfigRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/vodConfigs/%s", projectID, location, vodConfigID),
	}
	// Deletes the VOD config.
	op, err := client.DeleteVodConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("client.DeleteVodConfig: %w", err)
	}
	err = op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Deleted VOD config")
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.DeleteVodConfigRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodConfigName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteVodConfig {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String vodConfigId = "my-vod-config-id";

    deleteVodConfig(projectId, location, vodConfigId);
  }

  // Deletes a video on demand (VOD) config.
  public static void deleteVodConfig(String projectId, String location, String vodConfigId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      DeleteVodConfigRequest deleteVodConfigRequest =
          DeleteVodConfigRequest.newBuilder()
              .setName(VodConfigName.of(projectId, location, vodConfigId).toString())
              .build();

      videoStitcherServiceClient
          .deleteVodConfigAsync(deleteVodConfigRequest)
          .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Deleted VOD config");
    }
  }
}

Node.js

在尝试此示例之前,请按照Node.js Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// vodConfigId = 'my-vod-config-id';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function deleteVodConfig() {
  // Construct request
  const request = {
    name: stitcherClient.vodConfigPath(projectId, location, vodConfigId),
  };
  const [operation] = await stitcherClient.deleteVodConfig(request);
  await operation.promise();
  console.log('Deleted VOD config');
}

deleteVodConfig().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\DeleteVodConfigRequest;

/**
 * Deletes a VOD config.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the VOD config
 * @param string $vodConfigId         The ID of the VOD config
 */
function delete_vod_config(
    string $callingProjectId,
    string $location,
    string $vodConfigId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->vodConfigName($callingProjectId, $location, $vodConfigId);
    $request = (new DeleteVodConfigRequest())
        ->setName($formattedName);
    $operationResponse = $stitcherClient->deleteVodConfig($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print status
        printf('Deleted VOD config %s' . PHP_EOL, $vodConfigId);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import empty_pb2 as empty


def delete_vod_config(
    project_id: str, location: str, vod_config_id: str
) -> empty.Empty:
    """Deletes a VOD config.
    Args:
        project_id: The GCP project ID.
        location: The location of the VOD config.
        vod_config_id: The user-defined VOD config ID."""

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/vodConfigs/{vod_config_id}"
    operation = client.delete_vod_config(name=name)
    response = operation.result()
    print("Deleted VOD config")
    return response

Ruby

在尝试此示例之前,请按照Ruby Video Stitcher API 快速入门:使用 客户端库。 有关详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Delete a VOD config
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param vod_config_id [String] Your VOD config name (e.g. `my-vod-config`)
#
def delete_vod_config project_id:, location:, vod_config_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the VOD config.
  name = client.vod_config_path project: project_id, location: location,
                                vod_config: vod_config_id

  # Delete the VOD config.
  operation = client.delete_vod_config name: name

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print a success message.
  puts "Deleted VOD config"
end

删除 CDN 密钥

如需删除 CDN 密钥,请执行以下操作:

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;此值位于 IAM 设置页面上的项目编号字段中
  • LOCATION:CDN 密钥所在的位置; 请使用某个受支持的区域
    显示营业地点
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 密钥的用户定义标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "delete",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
此命令会创建一个 长时间运行的操作 (LRO) 您可以查询该 ID 以跟踪进度。如需了解详情,请参阅检查结果

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class DeleteCdnKeySample
{
    public async Task DeleteCdnKeyAsync(
        string projectId, string location, string cdnKeyId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        DeleteCdnKeyRequest request = new DeleteCdnKeyRequest
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId)
        };

        // Make the request.
        Operation<Empty, OperationMetadata> response = await client.DeleteCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        await response.PollUntilCompletedAsync();
    }
}

Go

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// deleteCDNKey deletes a CDN key.
func deleteCDNKey(w io.Writer, projectID, keyID string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID)

	req := &stitcherstreampb.DeleteCdnKeyRequest{
		Name: name,
	}
	// Deletes the CDN key.
	op, err := client.DeleteCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.DeleteCdnKey: %w", err)
	}
	err = op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Deleted CDN key")
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.CdnKeyName;
import com.google.cloud.video.stitcher.v1.DeleteCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteCdnKey {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";

    deleteCdnKey(projectId, location, cdnKeyId);
  }

  // Deletes a CDN key.
  public static void deleteCdnKey(String projectId, String location, String cdnKeyId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      DeleteCdnKeyRequest deleteCdnKeyRequest =
          DeleteCdnKeyRequest.newBuilder()
              .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
              .build();

      videoStitcherServiceClient
          .deleteCdnKeyAsync(deleteCdnKeyRequest)
          .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Deleted CDN key");
    }
  }
}

Node.js

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 有关详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// cdnKeyId = 'my-cdn-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function deleteCdnKey() {
  // Construct request
  const request = {
    name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
  };
  const [operation] = await stitcherClient.deleteCdnKey(request);
  await operation.promise();
  console.log('Deleted CDN key');
}

deleteCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在尝试此示例之前,请按照PHP Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\DeleteCdnKeyRequest;

/**
 * Deletes a CDN key.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the CDN key
 * @param string $cdnKeyId             The ID of the CDN key
 */
function delete_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $request = (new DeleteCdnKeyRequest())
        ->setName($formattedName);
    $operationResponse = $stitcherClient->deleteCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print status
        printf('Deleted CDN key %s' . PHP_EOL, $cdnKeyId);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在尝试此示例之前,请按照Python Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import empty_pb2 as empty


def delete_cdn_key(project_id: str, location: str, cdn_key_id: str) -> empty.Empty:
    """Deletes a CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN key.
        cdn_key_id: The user-defined CDN key ID."""

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/cdnKeys/{cdn_key_id}"
    operation = client.delete_cdn_key(name=name)
    response = operation.result()
    print("Deleted CDN key")
    return response

Ruby

在尝试此示例之前,请按照Ruby Video Stitcher API 快速入门:使用 客户端库。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Delete a CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] Your CDN key name (e.g. `my-cdn-key`)
#
def delete_cdn_key project_id:, location:, cdn_key_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the CDN key.
  name = client.cdn_key_path project: project_id, location: location,
                             cdn_key: cdn_key_id

  # Delete the CDN key.
  operation = client.delete_cdn_key name: name

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print a success message.
  puts "Deleted CDN key"
end

撤消凭据

  1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

    gcloud auth application-default revoke
  2. Optional: Revoke credentials from the gcloud CLI.

    gcloud auth revoke

后续步骤

查看 Video Stitcher API 参考文档