Membuat konfigurasi VOD

Buat konfigurasi VOD untuk diterapkan ke sesi VOD.

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Video Stitcher API.

Untuk melakukan autentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.