Membuat aset

Buat resource aset. Aset adalah video atau gambar yang dapat digunakan dengan Live Stream API.

Jelajahi lebih lanjut

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

Contoh kode

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

public class CreateAssetSample
{
    public async Task<Asset> CreateAssetAsync(
         string projectId, string locationId, string assetId, string assetUri)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        CreateAssetRequest request = new CreateAssetRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
            AssetId = assetId,
            Asset = new Asset
            {
                Video = new Asset.Types.VideoAsset
                {
                    Uri = assetUri
                }
            }
        };

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

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

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

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
)

// createAsset creates an asset. This asset references a video file
// in Cloud Storage.
func createAsset(w io.Writer, projectID, location, assetID, assetURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// assetID := "my-asset"
	// assetURI := "gs://my-bucket/my-video.mp4"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.CreateAssetRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		AssetId: assetID,
		Asset: &livestreampb.Asset{
			Resource: &livestreampb.Asset_Video{
				Video: &livestreampb.Asset_VideoAsset{
					Uri: assetURI,
				},
			},
		},
	}
	// Creates the asset.
	op, err := client.CreateAsset(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateAsset: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Asset: %v", response.Name)
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.video.livestream.v1.Asset;
import com.google.cloud.video.livestream.v1.Asset.VideoAsset;
import com.google.cloud.video.livestream.v1.CreateAssetRequest;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateAsset {

  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 assetId = "my-asset-id";
    String assetUri = "gs://my-bucket/my-video.mp4";

    createAsset(projectId, location, assetId, assetUri);
  }

  public static void createAsset(String projectId, String location, String assetId, String assetUri)
      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.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    var createAssetRequest =
        CreateAssetRequest.newBuilder()
            .setParent(LocationName.of(projectId, location).toString())
            .setAssetId(assetId)
            .setAsset(
                Asset.newBuilder()
                    .setVideo(
                        VideoAsset.newBuilder()
                            .setUri(assetUri)
                            .build())
                    .build())
            .build();
    // First API call in a project can take up to 15 minutes.
    Asset result =
        livestreamServiceClient.createAssetAsync(createAssetRequest).get(15, TimeUnit.MINUTES);
    System.out.println("Asset: " + result.getName());
    livestreamServiceClient.close();
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// assetId = 'my-asset';
// assetUri = 'gs://my-bucket/my-video.mp4';

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function createAsset() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.locationPath(projectId, location),
    assetId: assetId,
    asset: {
      video: {
        uri: assetUri,
      },
    },
  };

  // Run request
  const [operation] = await livestreamServiceClient.createAsset(request);
  const response = await operation.promise();
  const [asset] = response;
  console.log(`Asset: ${asset.name}`);
}

createAsset();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\Video\LiveStream\V1\Asset;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\CreateAssetRequest;

/**
 * Creates an asset. You can use an asset to create a slate.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the asset
 * @param string  $assetId            The ID of the asset to be created
 * @param string  $assetUri           The Cloud Storage URI of the asset
 */
function create_asset(
    string $callingProjectId,
    string $location,
    string $assetId,
    string $assetUri
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $parent = $livestreamClient->locationName($callingProjectId, $location);
    $asset = (new Asset())
        ->setVideo(
            (new Asset\VideoAsset())
                ->setUri($assetUri));

    // Run the asset creation request. The response is a long-running operation ID.
    $request = (new CreateAssetRequest())
        ->setParent($parent)
        ->setAsset($asset)
        ->setAssetId($assetId);
    $operationResponse = $livestreamClient->createAsset($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Asset: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import argparse

from google.cloud.video import live_stream_v1
from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)

def create_asset(
    project_id: str, location: str, asset_id: str, asset_uri: str
) -> live_stream_v1.types.Asset:
    """Creates an asset.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the asset.
        asset_id: The user-defined asset ID.
        asset_uri: The asset URI (e.g., 'gs://my-bucket/my-video.mp4')."""

    client = LivestreamServiceClient()

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

    asset = live_stream_v1.types.Asset(
        video=live_stream_v1.types.Asset.VideoAsset(
            uri=asset_uri,
        )
    )
    operation = client.create_asset(parent=parent, asset=asset, asset_id=asset_id)
    response = operation.result(600)
    print(f"Asset: {response.name}")

    return response

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Live Stream API, lihat Library klien Live Stream API. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Live Stream API.

Untuk melakukan autentikasi ke Live Stream API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

require "google/cloud/video/live_stream"

##
# Create an asset
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param asset_id [String] Your asset name (e.g. "my-asset")
# @param asset_uri [String] Your asset URI (e.g. "gs://my-bucket/my-video.mp4")
#
def create_asset project_id:, location:, asset_id:, asset_uri:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

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

  # Set the asset fields.
  new_asset = {
    video: {
      uri: asset_uri
    }
  }

  operation = client.create_asset parent: parent, asset: new_asset, asset_id: asset_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 asset name.
  puts "Asset: #{operation.response.name}"
end

Langkah selanjutnya

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