Actualizar una configuración de VOD

Actualiza un recurso de configuración de vídeo a la carta de Video Stitcher.

Investigar más

Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:

Código de ejemplo

C#

Antes de probar este ejemplo, sigue las C# instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


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

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

        UpdateVodConfigRequest request = new UpdateVodConfigRequest
        {
            VodConfig = new VodConfig
            {
                VodConfigName = VodConfigName.FromProjectLocationVodConfig(projectId, location, vodConfigId),
                SourceUri = sourceUri,
            },
            UpdateMask = new FieldMask { Paths = { "sourceUri" } }
        };

        // Make the request.
        Operation<VodConfig, OperationMetadata> response = await client.UpdateVodConfigAsync(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

Antes de probar este ejemplo, sigue las Go instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateVodConfig updates an existing VOD config. This sample updates the sourceURI for an
// existing VOD config.
func updateVodConfig(w io.Writer, projectID, vodConfigID, sourceURI string) error {
	// projectID := "my-project-id"
	// vodConfigID := "my-vod-config-id"
	// sourceURI := "https://storage.googleapis.com/my-bucket/main.mpd"
	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.UpdateVodConfigRequest{
		VodConfig: &stitcherstreampb.VodConfig{
			Name:      fmt.Sprintf("projects/%s/locations/%s/vodConfigs/%s", projectID, location, vodConfigID),
			SourceUri: sourceURI,
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"sourceUri",
			},
		},
	}
	// Updates the VOD config.
	op, err := client.UpdateVodConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("client.UpdateVodConfig: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

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

Java

Antes de probar este ejemplo, sigue las Java instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


import com.google.cloud.video.stitcher.v1.UpdateVodConfigRequest;
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 com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateVodConfig {

  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";
    // Updated 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";

    updateVodConfig(projectId, location, vodConfigId, sourceUri);
  }

  // Updates the source URI in a video on demand (VOD) config.
  public static VodConfig updateVodConfig(
      String projectId, String location, String vodConfigId, String sourceUri)
      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()) {
      UpdateVodConfigRequest updateVodConfigRequest =
          UpdateVodConfigRequest.newBuilder()
              .setVodConfig(
                  VodConfig.newBuilder()
                      .setName(VodConfigName.of(projectId, location, vodConfigId).toString())
                      .setSourceUri(sourceUri)
                      .build())
              // Set the update mask to the sourceUri field in the existing VOD config. You must set
              // the mask to the field you want to update.
              .setUpdateMask(FieldMask.newBuilder().addPaths("sourceUri").build())
              .build();

      VodConfig response =
          videoStitcherServiceClient
              .updateVodConfigAsync(updateVodConfigRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Updated VOD config: " + response.getName());
      return response;
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las Node.js instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

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

async function updateVodConfig() {
  // Construct request
  const request = {
    vodConfig: {
      name: stitcherClient.vodConfigPath(projectId, location, vodConfigId),
      sourceUri: sourceUri,
    },
    updateMask: {
      paths: ['sourceUri'],
    },
  };

  const [operation] = await stitcherClient.updateVodConfig(request);
  const [response] = await operation.promise();
  console.log(`Updated VOD config: ${response.name}`);
  console.log(`Updated sourceUri: ${response.sourceUri}`);
}

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

PHP

Antes de probar este ejemplo, sigue las PHP instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API PHP Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\UpdateVodConfigRequest;
use Google\Cloud\Video\Stitcher\V1\VodConfig;
use Google\Protobuf\FieldMask;

/**
 * Updates the VOD config's sourceUri field.
 *
 * @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 update
 * @param string $sourceUri            Updated uri of the media to stitch; this URI must
 *                                     reference either an MPEG-DASH manifest
 *                                     (.mpd) file or an M3U playlist manifest
 *                                     (.m3u8) file.
 */
function update_vod_config(
    string $callingProjectId,
    string $location,
    string $vodConfigId,
    string $sourceUri
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->vodConfigName($callingProjectId, $location, $vodConfigId);
    $vodConfig = new VodConfig();
    $vodConfig->setName($formattedName);
    $vodConfig->setSourceUri($sourceUri);
    $updateMask = new FieldMask([
        'paths' => ['sourceUri']
    ]);

    // Run VOD config update request
    $request = (new UpdateVodConfigRequest())
        ->setVodConfig($vodConfig)
        ->setUpdateMask($updateMask);
    $operationResponse = $stitcherClient->updateVodConfig($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated VOD config: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Antes de probar este ejemplo, sigue las Python instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import field_mask_pb2 as field_mask


def update_vod_config(
    project_id: str, location: str, vod_config_id: str, vod_uri: str
) -> stitcher_v1.types.VodConfig:
    """Updates a VOD config.
    Args:
        project_id: The GCP project ID.
        location: The location of the VOD config.
        vod_config_id: The existing VOD config's ID.
        vod_uri: Updated URI of the VOD to stitch; this URI must reference
                    either an MPEG-DASH manifest (.mpd) file or an M3U playlist
                    manifest (.m3u8) file.

    Returns:
        The VOD config resource.
    """

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/vodConfigs/{vod_config_id}"
    vod_config = stitcher_v1.types.VodConfig(
        name=name,
        source_uri=vod_uri,
    )
    update_mask = field_mask.FieldMask(paths=["sourceUri"])

    operation = client.update_vod_config(vod_config=vod_config, update_mask=update_mask)
    response = operation.result()
    print(f"Updated VOD config: {response.name}")
    return response

Ruby

Antes de probar este ejemplo, sigue las Ruby instrucciones de configuración de la guía de inicio rápido de la API Video Stitcher con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Ruby Video Stitcher API.

Para autenticarte en la API Video Stitcher, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

require "google/cloud/video/stitcher"

##
# Update 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`)
# @param source_uri [String] Updated URI of the VOD stream to stitch
#   (e.g. `https://storage.googleapis.com/my-bucket/main.mpd`)
#
def update_vod_config project_id:, location:, vod_config_id:, source_uri:
  # 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

  # Set the update mask.
  update_mask = { paths: ["sourceUri"] }

  # Set the VOD config fields.
  update_vod_config = {
    name: name,
    source_uri: source_uri
  }

  operation = client.update_vod_config vod_config: update_vod_config, update_mask: update_mask

  # 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 and updated source URI.
  puts "Updated VOD config: #{operation.response.name}"
  puts "Updated source URI: #{operation.response.source_uri}"
end

Siguientes pasos

Para buscar y filtrar ejemplos de código de otros Google Cloud productos, consulta el Google Cloud navegador de ejemplos.