Creare una risorsa

Creare una risorsa asset. Le risorse sono video o immagini che possono essere utilizzati con l'API Live Stream.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C#

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per scoprire come installare e utilizzare la libreria client per l'API Live Stream, consulta la pagina dedicata alle librerie client dell'API Live Stream. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby per l'API Live Stream.

Per eseguire l'autenticazione all'API Live Stream, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.