VOD 애셋에 광고 삽입

이 페이지에서는 Video Stitcher API, curl, PowerShell 또는 클라이언트 라이브러리를 사용하여 주문형 동영상(VOD) 애셋 재생에 광고를 삽입하는 방법을 보여줍니다.

시작하기 전에

Video Stitcher API를 호출하기 전 다음 단계를 완료합니다.

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud CLI를 설치합니다.
  3. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  4. Google Cloud 프로젝트를 만들거나 선택합니다.

    • Google Cloud 프로젝트를 만듭니다.

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 만든 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID를 Google Cloud 프로젝트 이름으로 바꿉니다.

  5. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  6. Video Stitcher API를 사용 설정합니다.

    gcloud services enable videostitcher.googleapis.com
  7. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login
  8. Google 계정에 역할을 부여합니다. 다음 각 IAM 역할에 대해 다음 명령어를 한 번씩 실행합니다. roles/videostitcher.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID를 프로젝트 ID로 바꿉니다.
    • EMAIL_ADDRESS를 이메일 주소로 바꿉니다.
    • ROLE을 각 개별 역할로 바꿉니다.
  9. Google Cloud CLI를 설치합니다.
  10. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  11. Google Cloud 프로젝트를 만들거나 선택합니다.

    • Google Cloud 프로젝트를 만듭니다.

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 만든 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID를 Google Cloud 프로젝트 이름으로 바꿉니다.

  12. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  13. Video Stitcher API를 사용 설정합니다.

    gcloud services enable videostitcher.googleapis.com
  14. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login
  15. Google 계정에 역할을 부여합니다. 다음 각 IAM 역할에 대해 다음 명령어를 한 번씩 실행합니다. roles/videostitcher.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID를 프로젝트 ID로 바꿉니다.
    • EMAIL_ADDRESS를 이메일 주소로 바꿉니다.
    • ROLE을 각 개별 역할로 바꿉니다.
  16. 이 빠른 시작에서는 MPEG-DASH 매니페스트(.mpd) 파일 또는 HTTP 실시간 스트리밍(HLS) 매니페스트(.m3u8) 파일이 필요합니다. MP4 또는 MOV와 같은 다른 미디어 파일 유형으로부터 매니페스트 파일을 생성하도록 트랜스코딩 작업을 만들 수 있습니다.
  17. 이 빠른 시작에서 콘텐츠 전송 네트워크(CDN)를 사용할 수도 있습니다. CDN을 구성하지 않은 경우 다음 수정 사항을 적용하여 Media CDN 빠른 시작의 단계를 따르세요.
    1. MPEG-DASH 또는 HLS 매니페스트 파일 및 미디어 세그먼트를 Cloud Storage 버킷에 업로드합니다.
    2. Cloud Storage 버킷을 공개적으로 읽을 수 있도록 설정할 필요가 없습니다.
    3. 서명된 URL 또는 서명되지 않은 URL을 사용할 수 있습니다.

CDN 키 만들기

Video Stitcher API는 콘텐츠 전송 네트워크(CDN)에서 동영상을 가져올 수 있습니다. 동영상 애셋이 URL 서명으로 보호되는 경우 CDN 키를 Video Stitcher API에 등록해야 합니다.

CDN 키를 등록하려면 projects.locations.cdnKeys.create 메서드를 사용합니다.

REST(Media 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의 호스트 이름입니다(예: 35.190.60.252와 같은 IP 주소 또는 cdn.example.com과 같은 도메인 이름).
  • MEDIA_CDN_KEYNAME: Media CDN 키의 키 세트 이름
  • MEDIA_CDN_PRIVATE_KEY: base64로 인코딩된 문자열인 64바이트 Ed25519 비공개 키입니다. 자세한 내용은 Media 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)을 만듭니다. 다음 섹션에서 사용할 name 필드의 마지막 부분인 반환된 OPERATION_ID를 복사합니다.

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의 호스트 이름입니다(예: 35.190.60.252와 같은 IP 주소 또는 cdn.example.com과 같은 도메인 이름).
  • GCDN_KEYNAME: Cloud CDN 키의 이름입니다.
  • GCDN_PRIVATE_KEY: Cloud 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)을 만듭니다. 다음 섹션에서 사용할 name 필드의 마지막 부분인 반환된 OPERATION_ID를 복사합니다.

REST(Akamai 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의 호스트 이름입니다(예: 35.190.60.252와 같은 IP 주소 또는 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)을 만듭니다. 다음 섹션에서 사용할 name 필드의 마지막 부분인 반환된 OPERATION_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 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

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 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 void 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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    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());
    videoStitcherServiceClient.close();
  }
}

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();

PHP

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용PHP 설정 안내를 따르세요. 자세한 내용은 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"
    }
  }
}

세션 만들기

광고 병합 동영상의 세션을 만들려면 projects.locations.vodSessions.create 메서드를 사용합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER: IAM 설정 페이지에서 프로젝트 번호 필드에 있는 Google Cloud 프로젝트 번호입니다.
  • LOCATION: 세션을 만들 위치입니다. 지원되는 리전 중 하나를 사용합니다.
    위치 표시
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_URI: 병합할 미디어의 URI입니다. 이 URI는 MPEG-DASH 매니페스트(.mpd) 파일 또는 M3U 재생목록 매니페스트(.m3u8) 파일을 참조해야 합니다. 공개 URI 또는 CDN 키를 등록한 서명되지 않은 URI를 사용합니다.
  • AD_TAG_URI: 광고 태그의 공개 URI입니다. 아직 없으면 VMAP 프리롤 샘플을 사용할 수 있습니다.

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 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"
}

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 sourceUri, string adTagUri)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateVodSessionRequest request = new CreateVodSessionRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            VodSession = new VodSession
            {
                SourceUri = sourceUri,
                AdTagUri = adTagUri,
                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, sourceURI string) error {
	// projectID := "my-project-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.CreateVodSessionRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		VodSession: &stitcherstreampb.VodSession{
			SourceUri:  sourceURI,
			AdTagUri:   adTagURI,
			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.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";
    // Uri of the media 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...";
    createVodSession(projectId, location, sourceUri, adTagUri);
  }

  public static void createVodSession(
      String projectId, String location, String sourceUri, String adTagUri) 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. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CreateVodSessionRequest createVodSessionRequest =
          CreateVodSessionRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setVodSession(
                  VodSession.newBuilder()
                      .setSourceUri(sourceUri)
                      .setAdTagUri(adTagUri)
                      .setAdTracking(AdTracking.SERVER)
                      .build())
              .build();

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

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';
// 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 createVodSession() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    vodSession: {
      sourceUri: sourceUri,
      adTagUri: adTagUri,
      adTracking: 'SERVER',
    },
  };
  const [session] = await stitcherClient.createVodSession(request);
  console.log(`VOD session: ${session.name}`);
}

createVodSession();

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 $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_session(
    string $callingProjectId,
    string $location,
    string $sourceUri,
    string $adTagUri
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $vodSession = new VodSession();
    $vodSession->setSourceUri($sourceUri);
    $vodSession->setAdTagUri($adTagUri);
    $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

이 샘플을 사용해 보기 전에 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_session(
    project_id: str, location: str, source_uri: str, ad_tag_uri: 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.
        source_uri: Uri of the media 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 session resource.
    """

    client = VideoStitcherServiceClient()

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

    vod_session = stitcher_v1.types.VodSession(
        source_uri=source_uri, ad_tag_uri=ad_tag_uri, ad_tracking="SERVER"
    )

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

Ruby

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Ruby 설정 안내를 따르세요. 자세한 내용은 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 source_uri [String] The URI of an MPEG-DASH manifest (.mpd) file or
#   an M3U playlist manifest (.m3u8) file
#   (e.g. "https://storage.googleapis.com/my-bucket/main.mpd")
# @param ad_tag_uri [String] The URI of the ad tag. See VMAP Pre-roll at
#   https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags.
#
def create_vod_session project_id:, location:, 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 session fields.
  new_vod_session = {
    source_uri: source_uri,
    ad_tag_uri: ad_tag_uri,
    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 이벤트가 포함되지 않습니다. 이전 섹션과 비슷한 JSON 응답이 수신되면 광고 인코딩을 기다린 후 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"
}

광고 병합 VOD 세션 재생

응답 객체의 playUri 필드에서 URI를 사용하여 광고 병합 VOD 세션을 재생합니다. 이 VOD 세션을 Shaka Player에서 재생하려면 다음 단계를 완료합니다.

  1. 온라인 미디어 플레이어인 Shaka Player로 이동합니다.
  2. 상단 탐색 메뉴에서 커스텀 콘텐츠를 클릭합니다.
  3. 화면의 + 버튼을 클릭합니다.
  4. playUri 필드의 값(PLAY_URI)을 Manifest URL 상자에 붙여넣습니다.

  5. 이름 상자에 이름을 입력합니다.

  6. 저장을 클릭합니다.

  7. 재생을 클릭합니다.

동영상이 Cloud Storage 버킷에 있는 경우 버킷에서 버킷이 공개 상태이고 CORS가 사용 설정되었는지 확인합니다.

Transcoder API 샘플 동영상VMAP 프리롤 광고 태그 URL을 사용하는 광고 병합 동영상 예시를 참조하세요.

삭제

이 페이지에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 Google Cloud 프로젝트를 삭제하면 됩니다.

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)을 만듭니다. 자세한 내용은 결과 확인을 참조하세요.

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);
  }

  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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    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");
    videoStitcherServiceClient.close();
  }
}

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();

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\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

이 샘플을 사용해 보기 전에 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_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

이 샘플을 사용해 보기 전에 Video Stitcher API 빠른 시작: 클라이언트 라이브러리 사용Ruby 설정 안내를 따르세요. 자세한 내용은 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. 선택사항: 만든 사용자 인증 정보를 취소하고 로컬 사용자 인증 정보 파일을 삭제합니다.

    gcloud auth application-default revoke
  2. 선택사항: gcloud CLI에서 사용자 인증 정보를 취소합니다.

    gcloud auth revoke

다음 단계

Video Stitcher API 참조 문서 검토