Aggiornare un canale

Aggiornare una risorsa per il canale di live streaming.

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.Cloud.Video.LiveStream.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateChannelSample
{
    public async Task<Channel> UpdateChannelAsync(
         string projectId, string locationId, string channelId, string inputId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        InputAttachment inputAttachment = new InputAttachment
        {
            Key = "updated-input",
            InputAsInputName = InputName.FromProjectLocationInput(projectId, locationId, inputId)
        };

        UpdateChannelRequest request = new UpdateChannelRequest
        {
            Channel = new Channel
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId),
                InputAttachments = { inputAttachment }
            },
            UpdateMask = new FieldMask { Paths = { "input_attachments" } }
        };

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

        // Poll until the returned long-running operation is complete.
        Operation<Channel, 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"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateChannel updates an existing channel with a different input.
func updateChannel(w io.Writer, projectID, location, channelID, inputID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// inputID := "my-updated-input"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.UpdateChannelRequest{
		Channel: &livestreampb.Channel{
			Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
			InputAttachments: []*livestreampb.InputAttachment{
				{
					Key:   "updated-input",
					Input: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
				},
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"input_attachments",
			},
		},
	}
	// Updates the input.
	op, err := client.UpdateChannel(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateChannel: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Updated channel: %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.Channel;
import com.google.cloud.video.livestream.v1.ChannelName;
import com.google.cloud.video.livestream.v1.InputAttachment;
import com.google.cloud.video.livestream.v1.InputName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.UpdateChannelRequest;
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 UpdateChannel {

  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 channelId = "my-channel-id";
    String inputId = "my-input-id";

    updateChannel(projectId, location, channelId, inputId);
  }

  public static void updateChannel(
      String projectId, String location, String channelId, String inputId)
      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 updateChannelRequest =
        UpdateChannelRequest.newBuilder()
            .setChannel(
                Channel.newBuilder()
                    .setName(ChannelName.of(projectId, location, channelId).toString())
                    .addInputAttachments(
                        0,
                        InputAttachment.newBuilder()
                            .setKey("updated-input")
                            .setInput(InputName.of(projectId, location, inputId).toString())
                            .build()))
            .setUpdateMask(FieldMask.newBuilder().addPaths("input_attachments").build())
            .build();
    // First API call in a project can take up to 10 minutes.
    Channel result =
        livestreamServiceClient
            .updateChannelAsync(updateChannelRequest)
            .get(10, TimeUnit.MINUTES);
    System.out.println("Updated channel: " + 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';
// channelId = 'my-channel';
// inputId = 'my-input';

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

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

async function updateChannel() {
  // Construct request
  const request = {
    channel: {
      name: livestreamServiceClient.channelPath(
        projectId,
        location,
        channelId
      ),
      inputAttachments: [
        {
          key: 'updated-input',
          input: livestreamServiceClient.inputPath(
            projectId,
            location,
            inputId
          ),
        },
      ],
    },
    updateMask: {
      paths: ['input_attachments'],
    },
  };

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

updateChannel();

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\Channel;
use Google\Cloud\Video\LiveStream\V1\InputAttachment;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\UpdateChannelRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates an existing channel with a different input.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel and the input
 * @param string  $channelId          The ID of the channel to be updated
 * @param string  $inputId            The ID of the existing input
 */
function update_channel(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $inputId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $channelName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    $inputName = $livestreamClient->inputName($callingProjectId, $location, $inputId);

    $inputAttachment = (new InputAttachment())
        ->setKey('updated-input')
        ->setInput($inputName);
    $channel = (new Channel())
        ->setName($channelName)
        ->setInputAttachments([$inputAttachment]);

    $updateMask = new FieldMask([
        'paths' => ['input_attachments']
    ]);

    // Run the channel update request. The response is a long-running operation ID.
    $request = (new UpdateChannelRequest())
        ->setChannel($channel)
        ->setUpdateMask($updateMask);
    $operationResponse = $livestreamClient->updateChannel($request);

    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated channel: %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,
)
from google.protobuf import field_mask_pb2 as field_mask

def update_channel(
    project_id: str, location: str, channel_id: str, input_id: str
) -> live_stream_v1.types.Channel:
    """Updates a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID.
        input_id: The user-defined input ID for the new input."""

    client = LivestreamServiceClient()
    input = f"projects/{project_id}/locations/{location}/inputs/{input_id}"
    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"

    channel = live_stream_v1.types.Channel(
        name=name,
        input_attachments=[
            live_stream_v1.types.InputAttachment(
                key="updated-input",
                input=input,
            ),
        ],
    )
    update_mask = field_mask.FieldMask(paths=["input_attachments"])

    operation = client.update_channel(channel=channel, update_mask=update_mask)
    response = operation.result(600)
    print(f"Updated channel: {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"

##
# Update a channel
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param channel_id [String] Your channel name (e.g. "my-channel")
# @param input_id [String] The input name to update the channel with (e.g. "my-updated-input")
#
def update_channel project_id:, location:, channel_id:, input_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the channel.
  name = client.channel_path project: project_id, location: location, channel: channel_id

  # Build the resource name of the input.
  input = client.input_path project: project_id, location: location, input: input_id

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

  # Update the channel input_attachments config field.
  update_channel = {
    name: name,
    input_attachments: [
      {
        key: "updated-input",
        input: input
      }
    ]
  }

  operation = client.update_channel update_mask: update_mask, channel: update_channel

  # 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 channel name.
  puts "Updated channel: #{operation.response.name}"
  puts "Updated input_attachments config: #{operation.response.input_attachments[0].key}"
end

Passaggi successivi

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