Início rápido para uma stream em direto MPEG-DASH

Esta página mostra-lhe como criar uma tarefa de stream em direto MPEG-DASH básica usando as predefinições da API Live Stream e curl, o PowerShell ou as bibliotecas de cliente.

Antes de começar

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  4. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Live Stream API:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable livestream.googleapis.com
  8. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  9. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  10. Install the Google Cloud CLI.

  11. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  12. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  13. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  14. Verify that billing is enabled for your Google Cloud project.

  15. Enable the Live Stream API:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable livestream.googleapis.com
  16. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  17. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  18. Crie um contentor do Cloud Storage

    Crie um contentor do Cloud Storage para armazenar o manifesto e os ficheiros de segmentos da stream em direto.

  19. Create a Cloud Storage bucket:
    gcloud storage buckets create gs://BUCKET_NAME
    Replace BUCKET_NAME with a bucket name that meets the bucket naming requirements.

    Instale um codificador

    Para usar a API, precisa de um codificador para gerar streams de entrada que a API processa.

    Instale o ffmpeg, uma vez que esta página aborda a forma de usar o ffmpeg para gerar streams de entrada. Pode instalá-lo no Cloud Shell através do seguinte comando.

    sudo apt install ffmpeg
    

    Crie um ponto final de entrada

    Para iniciar uma stream em direto, tem de usar primeiro o método projects.locations.inputs.create para criar um ponto final de entrada. Envia o fluxo de entrada para este ponto final.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização na qual criar o ponto final de entrada; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • INPUT_ID: um identificador definido pelo utilizador para o novo ponto final de entrada a criar (para o qual envia a sua stream de entrada). Este valor tem de ter entre 1 e 63 carateres, começar e terminar com [a-z0-9] e pode conter travessões (-) entre carateres. Por exemplo, my-input.

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
        "verb": "create",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Video.LiveStream.V1;
    using Google.LongRunning;
    using System.Threading.Tasks;
    
    public class CreateInputSample
    {
        public async Task<Input> CreateInputAsync(
             string projectId, string locationId, string inputId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            CreateInputRequest request = new CreateInputRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
                InputId = inputId,
                Input = new Input
                {
                    Type = Input.Types.Type.RtmpPush
                }
            };
    
            // Make the request.
            Operation<Input, OperationMetadata> response = await client.CreateInputAsync(request);
    
            // Poll until the returned long-running operation is complete.
            Operation<Input, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
    
            // Retrieve the operation result.
            return completedResponse.Result;
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // createInput creates an input endpoint. You send an input video stream to this
    // endpoint.
    func createInput(w io.Writer, projectID, location, inputID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// inputID := "my-input"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.CreateInputRequest{
    		Parent:  fmt.Sprintf("projects/%s/locations/%s", projectID, location),
    		InputId: inputID,
    		Input: &livestreampb.Input{
    			Type: livestreampb.Input_RTMP_PUSH,
    		},
    	}
    	// Creates the input.
    	op, err := client.CreateInput(ctx, req)
    	if err != nil {
    		return fmt.Errorf("CreateInput: %w", err)
    	}
    	response, err := op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("Wait: %w", err)
    	}
    
    	fmt.Fprintf(w, "Input: %v", response.Name)
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.CreateInputRequest;
    import com.google.cloud.video.livestream.v1.Input;
    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 CreateInput {
    
      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 inputId = "my-input-id";
    
        createInput(projectId, location, inputId);
      }
    
      public static void createInput(String projectId, String location, 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 createInputRequest =
            CreateInputRequest.newBuilder()
                .setParent(LocationName.of(projectId, location).toString())
                .setInputId(inputId)
                .setInput(Input.newBuilder().setType(Input.Type.RTMP_PUSH).build())
                .build();
        // First API call in a project can take up to 15 minutes.
        Input result =
            livestreamServiceClient.createInputAsync(createInputRequest).get(15, TimeUnit.MINUTES);
        System.out.println("Input: " + result.getName());
        livestreamServiceClient.close();
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // inputId = 'my-input';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function createInput() {
      // Construct request
      const request = {
        parent: livestreamServiceClient.locationPath(projectId, location),
        inputId: inputId,
        input: {
          type: 'RTMP_PUSH',
        },
      };
    
      // Run request
      const [operation] = await livestreamServiceClient.createInput(request);
      const response = await operation.promise();
      const [input] = response;
      console.log(`Input: ${input.name}`);
    }
    
    createInput();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Input;
    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\CreateInputRequest;
    
    /**
     * Creates an input. You send an input video stream to this endpoint.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the input
     * @param string  $inputId            The ID of the input to be created
     */
    function create_input(
        string $callingProjectId,
        string $location,
        string $inputId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
    
        $parent = $livestreamClient->locationName($callingProjectId, $location);
        $input = (new Input())
            ->setType(Input\Type::RTMP_PUSH);
    
        // Run the input creation request. The response is a long-running operation ID.
        $request = (new CreateInputRequest())
            ->setParent($parent)
            ->setInput($input)
            ->setInputId($inputId);
        $operationResponse = $livestreamClient->createInput($request);
        $operationResponse->pollUntilComplete();
        if ($operationResponse->operationSucceeded()) {
            $result = $operationResponse->getResult();
            // Print results
            printf('Input: %s' . PHP_EOL, $result->getName());
        } else {
            $error = $operationResponse->getError();
            // handleError($error)
        }
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video import live_stream_v1
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    
    
    def create_input(
        project_id: str, location: str, input_id: str
    ) -> live_stream_v1.types.Input:
        """Creates an input.
        Args:
            project_id: The GCP project ID.
            location: The location in which to create the input.
            input_id: The user-defined input ID."""
    
        client = LivestreamServiceClient()
    
        parent = f"projects/{project_id}/locations/{location}"
    
        input = live_stream_v1.types.Input(
            type_="RTMP_PUSH",
        )
        operation = client.create_input(parent=parent, input=input, input_id=input_id)
        response = operation.result(900)
        print(f"Input: {response.name}")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Create an input endpoint
    #
    # @param project_id [String] Your Google Cloud project (e.g. "my-project")
    # @param location [String] The location (e.g. "us-central1")
    # @param input_id [String] Your input name (e.g. "my-input")
    #
    def create_input project_id:, location:, input_id:
      # 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 input fields.
      new_input = {
        type: Google::Cloud::Video::LiveStream::V1::Input::Type::RTMP_PUSH
      }
    
      operation = client.create_input parent: parent, input: new_input, input_id: input_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 input name.
      puts "Input: #{operation.response.name}"
    end

    Copie o OPERATION_ID devolvido para usar na secção seguinte.

    Verifique o resultado

    Use o método projects.locations.operations.get para verificar se o ponto final de entrada foi criado. Se a resposta contiver "done: false", repita o comando até que a resposta contenha "done: true". A criação do primeiro ponto final de entrada numa região pode demorar até 10 minutos.

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu ponto final de entrada está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • OPERATION_ID: o identificador da operação

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "endTime": END_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
        "verb": "create",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": true,
      "response": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.Input",
        "name": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
        "createTime": CREATE_TIME,
        "updateTime": UPDATE_TIME,
        "type": "RTMP_PUSH",
        "uri":  INPUT_STREAM_URI, # For example, "rtmp://1.2.3.4/live/b8ebdd94-c8d9-4d88-a16e-b963c43a953b",
        "tier": "HD"
      }
    }
    

    Encontre o campo uri e copie o INPUT_STREAM_URI devolvido para usar mais tarde na secção Envie o fluxo de entrada.

    Crie um canal

    Para transcodificar a stream de entrada numa stream de saída, tem de criar um recurso de canal.

    Para criar um canal, use o método projects.locations.channels.create. O exemplo seguinte cria um canal que gera uma stream em direto MPEG-DASH que consiste numa única renderização de alta definição (1280 x 720).

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização na qual criar o canal; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal a criar; este valor tem de ter entre 1 e 63 carateres, começar e terminar com [a-z0-9] e pode conter traços (-) entre carateres
    • INPUT_ID: o identificador definido pelo utilizador para o ponto final de entrada
    • BUCKET_NAME: o nome do contentor do Cloud Storage que criou para conter o manifesto da stream em direto e os ficheiros de segmentos

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
        "verb": "create",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    Aceda ao canal

    Pode verificar o resultado da operação de criação do canal através do novo ID da operação.

    Depois de criar o canal, use o método projects.locations.channels.get para consultar o estado do canal.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "inputAttachments": [
        {
          "key": "INPUT_ID",
          "input": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID"
        }
      ],
      "activeInput": "INPUT_ID",
      "output": {
        "uri": "gs://BUCKET_NAME"
      },
      "elementaryStreams": [
        {
          "videoStream": {
            "h264": {
              "widthPixels": 1280,
              "heightPixels": 720,
              "frameRate": 30,
              "bitrateBps": 3000000,
              "gopDuration": "2s",
              "vbvSizeBits": 3000000,
              "vbvFullnessBits": 2700000,
              "entropyCoder": "cabac",
              "profile": "high"
            }
          },
          "key": "es_video"
        },
        {
          "audioStream": {
            "codec": "aac",
            "bitrateBps": 160000,
            "channelCount": 2,
            "channelLayout": ["fl", "fr"],
            "sampleRateHertz": 48000
          },
          "key": "es_audio"
        }
      ],
      "muxStreams": [
        {
          "key": "mux_video",
          "container": "fmp4",
          "elementaryStreams": ["es_video"],
          "segmentSettings": { "segmentDuration": "2s" }
        },
        {
          "key": "mux_audio",
          "container": "fmp4",
          "elementaryStreams": ["es_audio"],
          "segmentSettings": { "segmentDuration": "2s" }
        }
      ],
      "manifests": [
        {
          "key": "manifest_dash",
          "fileName": "main.mpd",
          "type": "DASH",
          "muxStreams": [
            "mux_video",
            "mux_audio"
          ],
          "maxSegmentCount": 5,
          "segmentKeepDuration": "60s"
        }
      ],
      "streamingState": "STOPPED"
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    
    public class GetChannelSample
    {
        public Channel GetChannel(
             string projectId, string locationId, string channelId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            GetChannelRequest request = new GetChannelRequest
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
            };
    
            // Make the request.
            Channel response = client.GetChannel(request);
            return response;
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // getChannel gets a previously-created channel.
    func getChannel(w io.Writer, projectID, location, channelID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel-id"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.GetChannelRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
    	}
    
    	response, err := client.GetChannel(ctx, req)
    	if err != nil {
    		return fmt.Errorf("GetChannel: %w", err)
    	}
    
    	fmt.Fprintf(w, "Channel: %v", response.Name)
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.Channel;
    import com.google.cloud.video.livestream.v1.ChannelName;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    
    public class GetChannel {
    
      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";
    
        getChannel(projectId, location, channelId);
      }
    
      public static void getChannel(String projectId, String location, String channelId)
          throws 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. In this example, try-with-resources is used
        // which automatically calls close() on the client to clean up resources.
        try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
          ChannelName name = ChannelName.of(projectId, location, channelId);
          Channel response = livestreamServiceClient.getChannel(name);
          System.out.println("Channel: " + response.getName());
        }
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function getChannel() {
      // Construct request
      const request = {
        name: livestreamServiceClient.channelPath(projectId, location, channelId),
      };
      const [channel] = await livestreamServiceClient.getChannel(request);
      console.log(`Channel: ${channel.name}`);
    }
    
    getChannel();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\GetChannelRequest;
    
    /**
     * Gets a channel.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel
     */
    function get_channel(
        string $callingProjectId,
        string $location,
        string $channelId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    
        // Get the channel.
        $request = (new GetChannelRequest())
            ->setName($formattedName);
        $response = $livestreamClient->getChannel($request);
        // Print results
        printf('Channel: %s' . PHP_EOL, $response->getName());
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video import live_stream_v1
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    
    
    def get_channel(
        project_id: str, location: str, channel_id: str
    ) -> live_stream_v1.types.Channel:
        """Gets a channel.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
        response = client.get_channel(name=name)
        print(f"Channel: {response.name}")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Get 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")
    #
    def get_channel project_id:, location:, channel_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
    
      # Get the channel.
      channel = client.get_channel name: name
    
      # Print the channel name.
      puts "Channel: #{channel.name}"
    end

    A resposta completa contém o seguinte campo. (Alguns dos exemplos de código acima apenas devolvem determinados campos na resposta, mas podem ser modificados para devolver a resposta completa.)

    {
      ...
      "streamingState": "STOPPED"
      ...
    }
    

    Esta resposta indica que já pode iniciar o canal.

    Inicie o canal

    Use o método projects.locations.channels.start para iniciar o canal. Tem de iniciar um canal antes de poder aceitar streams de entrada ou gerar uma stream de saída.

    O início do primeiro canal numa região demora cerca de 10 minutos.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
        "verb": "start",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    using Google.LongRunning;
    using System.Threading.Tasks;
    
    public class StartChannelSample
    {
        public async Task StartChannelAsync(
             string projectId, string locationId, string channelId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            StartChannelRequest request = new StartChannelRequest
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
            };
    
            // Make the request.
            Operation<ChannelOperationResponse, OperationMetadata> response = await client.StartChannelAsync(request);
    
            // Poll until the returned long-running operation is complete.
            await response.PollUntilCompletedAsync();
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // startChannel starts a channel.
    func startChannel(w io.Writer, projectID, location, channelID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel-id"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.StartChannelRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
    	}
    
    	op, err := client.StartChannel(ctx, req)
    	if err != nil {
    		return fmt.Errorf("StartChannel: %w", err)
    	}
    	_, err = op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("Wait: %w", err)
    	}
    
    	fmt.Fprintf(w, "Started channel")
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.ChannelName;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class StartChannel {
    
      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";
    
        startChannel(projectId, location, channelId);
      }
    
      public static void startChannel(String projectId, String location, String channelId)
          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();
        ChannelName name = ChannelName.of(projectId, location, channelId);
        // First API call in a project can take up to 15 minutes.
        livestreamServiceClient.startChannelAsync(name).get(15, TimeUnit.MINUTES);
        System.out.println("Started channel");
        livestreamServiceClient.close();
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function startChannel() {
      // Construct request
      const request = {
        name: livestreamServiceClient.channelPath(projectId, location, channelId),
      };
      const [operation] = await livestreamServiceClient.startChannel(request);
      await operation.promise();
      console.log('Started channel');
    }
    
    startChannel();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\StartChannelRequest;
    
    /**
     * Starts a channel.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel
     */
    function start_channel(
        string $callingProjectId,
        string $location,
        string $channelId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    
        // Run the channel start request. The response is a long-running operation ID.
        $request = (new StartChannelRequest())
            ->setName($formattedName);
        $operationResponse = $livestreamClient->startChannel($request);
        $operationResponse->pollUntilComplete();
        if ($operationResponse->operationSucceeded()) {
            // Print results
            printf('Started channel' . PHP_EOL);
        } else {
            $error = $operationResponse->getError();
            // handleError($error)
        }
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video import live_stream_v1
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    
    
    def start_channel(
        project_id: str, location: str, channel_id: str
    ) -> live_stream_v1.types.ChannelOperationResponse:
        """Starts a channel.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
        operation = client.start_channel(name=name)
        response = operation.result(900)
        print("Started channel")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Starts 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")
    #
    def start_channel project_id:, location:, channel_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
    
      # Start the channel.
      operation = client.start_channel name: name
    
      # 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 a success message.
      puts "Started channel"
    end

    Envie a stream de entrada

    Para determinar se o canal foi iniciado, aceda às informações do canal como fez anteriormente. A resposta deve conter o seguinte:

    {
      ...
      "streamingState": "AWAITING_INPUT"
      ...
    }
    

    Agora que o canal está pronto, envie uma stream de entrada de teste para o ponto final de entrada para gerar a stream em direto.

    Abra uma nova janela de terminal. Execute o seguinte comando, usando o INPUT_STREAM_URI da secção Verifique o resultado:

    ffmpeg -re -f lavfi -i "testsrc=size=1280x720 [out0]; sine=frequency=500 [out1]" \
      -acodec aac -vcodec h264 -f flv INPUT_STREAM_URI
    

    Verifique se o canal está em streaming

    Para verificar o estado da operação de streaming em direto, obtenha as informações do canal, como fez anteriormente. A resposta deve conter o seguinte:

    {
      ...
      "streamingState": "STREAMING"
      ...
    }
    

    Valide o conteúdo no contentor do Cloud Storage

    Abra o contentor do Cloud Storage. Verifique se contém os seguintes ficheiros e diretórios:

    • main.mpd
    • mux_audio/
      • Vários ficheiros segment-segment-number.m4s
      • Um único ficheiro segment-initialization_segment_0000000000.m4s
    • mux_video/
      • Vários ficheiros segment-segment-number.m4s
      • Um único ficheiro segment-initialization_segment_0000000000.m4s

    Veja a stream em direto gerada

    Para reproduzir o ficheiro multimédia gerado no Shaka Player, conclua os seguintes passos:

    1. Torne o contentor do Cloud Storage que criou publicamente legível.
    2. Para ativar a partilha de recursos de origem cruzada (CORS) num contentor do Cloud Storage, faça o seguinte:
      1. Crie um ficheiro JSON que contenha o seguinte:
        [
          {
            "origin": ["https://shaka-player-demo.appspot.com/"],
            "responseHeader": ["Content-Type", "Range"],
            "method": ["GET", "HEAD"],
            "maxAgeSeconds": 3600
          }
        ]
      2. Execute o seguinte comando depois de substituir JSON_FILE_NAME pelo nome do ficheiro JSON que criou no passo anterior:
        gcloud storage buckets update gs://BUCKET_NAME --cors-file=JSON_FILE_NAME.json
    3. No contentor do Cloud Storage, encontre o ficheiro gerado.main.mpd Clique em Copiar URL na coluna Acesso público do ficheiro.
    4. Navegue para Shaka Player, um leitor de streams em direto online.
    5. Clique em Conteúdo personalizado na barra de navegação superior.
    6. Clique no botão +.
    7. Cole o URL público do ficheiro na caixa URL do manifesto.

    8. Introduza um nome na caixa Nome.

    9. Clique em Guardar.

    10. Clique em Jogar.

    Deve ver um padrão de teste a ser reproduzido como stream em direto.

    Vídeo de padrão de teste

    Adicione um marcador de pausa para anúncios à stream em direto

    Use o método projects.locations.channels.events.create para adicionar um marcador de pausa para anúncios à stream em direto.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal
    • EVENT_ID: um identificador definido pelo utilizador para o evento

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID/events/EVENT_ID",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "adBreak": {
        "duration": "100s"
      },
      "executeNow": true,
      "state": "PENDING"
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    
    public class CreateChannelEventSample
    {
        public Event CreateChannelEvent(
             string projectId, string locationId, string channelId, string eventId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            CreateEventRequest request = new CreateEventRequest
            {
                ParentAsChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId),
                EventId = eventId,
                Event = new Event
                {
                    AdBreak = new Event.Types.AdBreakTask
                    {
                        Duration = new Google.Protobuf.WellKnownTypes.Duration
                        {
                            Seconds = 30
                        }
                    },
                    ExecuteNow = true
                }
            };
    
            // Make the request.
            Event response = client.CreateEvent(request);
            return response;
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"github.com/golang/protobuf/ptypes/duration"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // createChannelEvent creates a channel event. An event is a sub-resource of a
    // channel, which can be scheduled by the user to execute operations on a
    // channel resource without having to stop the channel. This sample creates an
    // ad break event.
    func createChannelEvent(w io.Writer, projectID, location, channelID, eventID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel"
    	// eventID := "my-channel-event"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.CreateEventRequest{
    		Parent:  fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
    		EventId: eventID,
    		Event: &livestreampb.Event{
    			Task: &livestreampb.Event_AdBreak{
    				AdBreak: &livestreampb.Event_AdBreakTask{
    					Duration: &duration.Duration{
    						Seconds: 30,
    					},
    				},
    			},
    			ExecuteNow: true,
    		},
    	}
    	// Creates the channel event.
    	response, err := client.CreateEvent(ctx, req)
    	if err != nil {
    		return fmt.Errorf("CreateEvent: %w", err)
    	}
    
    	fmt.Fprintf(w, "Channel event: %v", response.Name)
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.ChannelName;
    import com.google.cloud.video.livestream.v1.CreateEventRequest;
    import com.google.cloud.video.livestream.v1.Event;
    import com.google.cloud.video.livestream.v1.Event.AdBreakTask;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import com.google.protobuf.Duration;
    import java.io.IOException;
    
    public class CreateChannelEvent {
    
      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 eventId = "my-channel-event-id";
    
        createChannelEvent(projectId, location, channelId, eventId);
      }
    
      public static void createChannelEvent(
          String projectId, String location, String channelId, String eventId) throws 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. In this example, try-with-resources is used
        // which automatically calls close() on the client to clean up resources.
        try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
          var createEventRequest =
              CreateEventRequest.newBuilder()
                  .setParent(ChannelName.of(projectId, location, channelId).toString())
                  .setEventId(eventId)
                  .setEvent(
                      Event.newBuilder()
                          .setAdBreak(
                              AdBreakTask.newBuilder()
                                  .setDuration(Duration.newBuilder().setSeconds(30).build())
                                  .build())
                          .setExecuteNow(true)
                          .build())
                  .build();
    
          Event response = livestreamServiceClient.createEvent(createEventRequest);
          System.out.println("Channel event: " + response.getName());
        }
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    // eventId = 'my-channel-event';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function createChannelEvent() {
      // Construct request
      const request = {
        parent: livestreamServiceClient.channelPath(
          projectId,
          location,
          channelId
        ),
        eventId: eventId,
        event: {
          adBreak: {
            duration: {
              seconds: 30,
            },
          },
          executeNow: true,
        },
      };
    
      // Run request
      const [event] = await livestreamServiceClient.createEvent(request);
      console.log(`Channel event: ${event.name}`);
    }
    
    createChannelEvent();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Event;
    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\CreateEventRequest;
    use Google\Protobuf\Duration;
    
    /**
     * Creates a channel event. This particular sample inserts an ad break marker.
     * Other event types are supported.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel
     * @param string  $eventId            The ID of the channel event
     */
    function create_channel_event(
        string $callingProjectId,
        string $location,
        string $channelId,
        string $eventId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
    
        $parent = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    
        $eventAdBreak = (new Event\AdBreakTask())
            ->setDuration(new Duration(['seconds' => 30]));
        $event = (new Event())
            ->setAdBreak($eventAdBreak)
            ->setExecuteNow(true);
    
        // Run the channel event creation request.
        $request = (new CreateEventRequest())
            ->setParent($parent)
            ->setEvent($event)
            ->setEventId($eventId);
        $response = $livestreamClient->createEvent($request);
        // Print results.
        printf('Channel event: %s' . PHP_EOL, $response->getName());
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    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 duration_pb2 as duration
    
    
    def create_channel_event(
        project_id: str, location: str, channel_id: str, event_id: str
    ) -> live_stream_v1.types.Event:
        """Creates a channel event.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID.
            event_id: The user-defined event ID."""
    
        client = LivestreamServiceClient()
        parent = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}/events/{event_id}"
    
        event = live_stream_v1.types.Event(
            name=name,
            ad_break=live_stream_v1.types.Event.AdBreakTask(
                duration=duration.Duration(
                    seconds=30,
                ),
            ),
            execute_now=True,
        )
    
        response = client.create_event(parent=parent, event=event, event_id=event_id)
        print(f"Channel event: {response.name}")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Create a channel event
    #
    # @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 event_id [String] Your event name (e.g. "my-event")
    #
    def create_channel_event project_id:, location:, channel_id:, event_id:
      # Create a Live Stream client.
      client = Google::Cloud::Video::LiveStream.livestream_service
    
      # Build the resource name of the parent.
      parent = client.channel_path project: project_id, location: location, channel: channel_id
    
      # Set the event fields.
      new_event = {
        ad_break: {
          duration: {
            seconds: 100
          }
        },
        execute_now: true
      }
    
      response = client.create_event parent: parent, event: new_event, event_id: event_id
    
      # Print the channel event name.
      puts "Channel event: #{response.name}"
    end

    Verifique se o marcador de pausa para anúncio existe

    Quando o marcador de anúncio é inserido na stream em direto, aparece um evento etiquetado como <SpliceInfoSection> no manifesto DASH para a duração do anúncio especificada (100 s).

    Execute o seguinte comando para ver o conteúdo do manifesto DASH gerado:

    gcloud storage cat gs://BUCKET_NAME/main.mpd

    Pode ter de executar o comando gcloud storage cat várias vezes até aparecer a secção <SpliceInfoSection>:

    <EventStream timescale="10000000" schemeIdUri="urn:scte:scte35:2013:xml">
      <Event duration="100000000" id="809">
        <SpliceInfoSection xmlns="urn:scte:scte35:2013:xml">
          <SpliceInsert outOfNetworkIndicator="true" spliceImmediateFlag="true">
            <BreakDuration autoReturn="true" duration="100000000"/>
          </SpliceInsert>
        </SpliceInfoSection>
      </Event>
    </EventStream>
    

    Limpar

    Para evitar incorrer em custos na sua Google Cloud conta pelos recursos usados nesta página, elimine o Google Cloud projeto com os recursos.

    Pare o canal

    Use o método projects.locations.channels.stop para parar o canal. Tem de parar o canal antes de o poder eliminar.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
        "verb": "stop",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    using Google.LongRunning;
    using System.Threading.Tasks;
    
    public class StopChannelSample
    {
        public async Task StopChannelAsync(
             string projectId, string locationId, string channelId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            StopChannelRequest request = new StopChannelRequest
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
            };
    
            // Make the request.
            Operation<ChannelOperationResponse, OperationMetadata> response = await client.StopChannelAsync(request);
    
            // Poll until the returned long-running operation is complete.
            await response.PollUntilCompletedAsync();
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // stopChannel stops a channel.
    func stopChannel(w io.Writer, projectID, location, channelID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel-id"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.StopChannelRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
    	}
    
    	op, err := client.StopChannel(ctx, req)
    	if err != nil {
    		return fmt.Errorf("StopChannel: %w", err)
    	}
    	_, err = op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("Wait: %w", err)
    	}
    
    	fmt.Fprintf(w, "Stopped channel")
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.ChannelName;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class StopChannel {
    
      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";
    
        stopChannel(projectId, location, channelId);
      }
    
      public static void stopChannel(String projectId, String location, String channelId)
          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();
        ChannelName name = ChannelName.of(projectId, location, channelId);
        // First API call in a project can take up to 10 minutes.
        livestreamServiceClient.stopChannelAsync(name).get(10, TimeUnit.MINUTES);
        System.out.println("Stopped channel");
        livestreamServiceClient.close();
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function stopChannel() {
      // Construct request
      const request = {
        name: livestreamServiceClient.channelPath(projectId, location, channelId),
      };
      const [operation] = await livestreamServiceClient.stopChannel(request);
      await operation.promise();
      console.log('Stopped channel');
    }
    
    stopChannel();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\StopChannelRequest;
    
    /**
     * Stops a channel.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel
     */
    function stop_channel(
        string $callingProjectId,
        string $location,
        string $channelId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    
        // Run the channel stop request. The response is a long-running operation ID.
        $request = (new StopChannelRequest())
            ->setName($formattedName);
        $operationResponse = $livestreamClient->stopChannel($request);
        $operationResponse->pollUntilComplete();
        if ($operationResponse->operationSucceeded()) {
            // Print results
            printf('Stopped channel' . PHP_EOL);
        } else {
            $error = $operationResponse->getError();
            // handleError($error)
        }
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video import live_stream_v1
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    
    
    def stop_channel(
        project_id: str, location: str, channel_id: str
    ) -> live_stream_v1.types.ChannelOperationResponse:
        """Stops a channel.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
        operation = client.stop_channel(name=name)
        response = operation.result(600)
        print("Stopped channel")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Stops 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")
    #
    def stop_channel project_id:, location:, channel_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
    
      # Stop the channel.
      operation = client.stop_channel name: name
    
      # 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 a success message.
      puts "Stopped channel"
    end

    Use o comando OPERATION_ID para verificar o estado da operação até receber "done":true no resultado.

    Pare a stream de entrada

    Se usou ffmpeg para enviar a stream de entrada, a ligação é automaticamente interrompida depois de parar o canal.

    Se usou outros codificadores com mecanismos de repetição, pode ter de parar manualmente a stream de entrada.

    Elimine o evento

    Use o método projects.locations.channels.events.delete para eliminar o evento de pausa para anúncios. Tem de eliminar os eventos do canal antes de poder eliminar o canal.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal
    • EVENT_ID: um identificador definido pelo utilizador para o evento

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {}
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    
    public class DeleteChannelEventSample
    {
        public void DeleteChannelEvent(
             string projectId, string locationId, string channelId, string eventId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            DeleteEventRequest request = new DeleteEventRequest
            {
                EventName = EventName.FromProjectLocationChannelEvent(projectId, locationId, channelId, eventId),
            };
    
            // Make the request.
            client.DeleteEvent(request);
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // deleteChannelEvent deletes a previously-created channel event.
    func deleteChannelEvent(w io.Writer, projectID, location, channelID, eventID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel"
    	// eventID := "my-channel-event"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.DeleteEventRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s/events/%s", projectID, location, channelID, eventID),
    	}
    
    	err = client.DeleteEvent(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteEvent: %w", err)
    	}
    
    	fmt.Fprintf(w, "Deleted channel event")
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.DeleteEventRequest;
    import com.google.cloud.video.livestream.v1.EventName;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    
    public class DeleteChannelEvent {
    
      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 eventId = "my-channel-event-id";
    
        deleteChannelEvent(projectId, location, channelId, eventId);
      }
    
      public static void deleteChannelEvent(
          String projectId, String location, String channelId, String eventId) throws 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. In this example, try-with-resources is used
        // which automatically calls close() on the client to clean up resources.
        try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
          var deleteEventRequest =
              DeleteEventRequest.newBuilder()
                  .setName(EventName.of(projectId, location, channelId, eventId).toString())
                  .build();
    
          livestreamServiceClient.deleteEvent(deleteEventRequest);
          System.out.println("Deleted channel event");
        }
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    // eventId = 'my-channel-event';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function deleteChannelEvent() {
      // Construct request
      const request = {
        name: livestreamServiceClient.eventPath(
          projectId,
          location,
          channelId,
          eventId
        ),
      };
    
      // Run request
      await livestreamServiceClient.deleteEvent(request);
      console.log('Deleted channel event');
    }
    
    deleteChannelEvent();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\DeleteEventRequest;
    
    /**
     * Deletes a channel event.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel
     * @param string  $eventId            The ID of the channel event to be deleted
     */
    function delete_channel_event(
        string $callingProjectId,
        string $location,
        string $channelId,
        string $eventId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->eventName($callingProjectId, $location, $channelId, $eventId);
    
        // Run the channel event deletion request.
        $request = (new DeleteEventRequest())
            ->setName($formattedName);
        $livestreamClient->deleteEvent($request);
        printf('Deleted channel event %s' . PHP_EOL, $eventId);
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    
    
    def delete_channel_event(
        project_id: str, location: str, channel_id: str, event_id: str
    ) -> None:
        """Deletes a channel event.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID.
            event_id: The user-defined event ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}/events/{event_id}"
        response = client.delete_event(name=name)
        print("Deleted channel event")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Delete a channel event
    #
    # @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 event_id [String] Your event name (e.g. "my-event")
    #
    def delete_channel_event project_id:, location:, channel_id:, event_id:
      # Create a Live Stream client.
      client = Google::Cloud::Video::LiveStream.livestream_service
    
      # Build the resource name of the channel event.
      name = client.event_path project: project_id, location: location, channel: channel_id, event: event_id
    
      # Delete the channel event.
      client.delete_event name: name
    
      # Print a success message.
      puts "Deleted channel event"
    end

    Eliminar o canal

    Use o método projects.locations.channels.delete para eliminar o canal. Tem de eliminar o canal antes de poder eliminar o ponto final de entrada usado pelo canal.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu canal está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • CHANNEL_ID: um identificador definido pelo utilizador para o canal

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
        "verb": "delete",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;
    
    public class DeleteChannelSample
    {
        public async Task DeleteChannelAsync(
             string projectId, string locationId, string channelId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            DeleteChannelRequest request = new DeleteChannelRequest
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
            };
    
            // Make the request.
            Operation<Empty, OperationMetadata> response = await client.DeleteChannelAsync(request);
    
            // Poll until the returned long-running operation is complete.
            await response.PollUntilCompletedAsync();
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // deleteChannel deletes a previously-created channel.
    func deleteChannel(w io.Writer, projectID, location, channelID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// channelID := "my-channel"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.DeleteChannelRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
    	}
    
    	op, err := client.DeleteChannel(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteChannel: %w", err)
    	}
    	err = op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("Wait: %w", err)
    	}
    
    	fmt.Fprintf(w, "Deleted channel")
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.ChannelName;
    import com.google.cloud.video.livestream.v1.DeleteChannelRequest;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class DeleteChannel {
    
      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";
    
        deleteChannel(projectId, location, channelId);
      }
    
      public static void deleteChannel(String projectId, String location, String channelId)
          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 deleteChannelRequest =
            DeleteChannelRequest.newBuilder()
                .setName(ChannelName.of(projectId, location, channelId).toString())
                .build();
        // First API call in a project can take up to 10 minutes.
        livestreamServiceClient.deleteChannelAsync(deleteChannelRequest).get(10, TimeUnit.MINUTES);
        System.out.println("Deleted channel");
        livestreamServiceClient.close();
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // channelId = 'my-channel';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function deleteChannel() {
      // Construct request
      const request = {
        name: livestreamServiceClient.channelPath(projectId, location, channelId),
      };
    
      // Run request
      const [operation] = await livestreamServiceClient.deleteChannel(request);
      await operation.promise();
      console.log('Deleted channel');
    }
    
    deleteChannel();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\DeleteChannelRequest;
    
    /**
     * Deletes a channel.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the channel
     * @param string  $channelId          The ID of the channel to be deleted
     */
    function delete_channel(
        string $callingProjectId,
        string $location,
        string $channelId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    
        // Run the channel deletion request. The response is a long-running operation ID.
        $request = (new DeleteChannelRequest())
            ->setName($formattedName);
        $operationResponse = $livestreamClient->deleteChannel($request);
        $operationResponse->pollUntilComplete();
        if ($operationResponse->operationSucceeded()) {
            // Print status
            printf('Deleted channel %s' . PHP_EOL, $channelId);
        } else {
            $error = $operationResponse->getError();
            // handleError($error)
        }
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    from google.protobuf import empty_pb2 as empty
    
    
    def delete_channel(project_id: str, location: str, channel_id: str) -> empty.Empty:
        """Deletes a channel.
        Args:
            project_id: The GCP project ID.
            location: The location of the channel.
            channel_id: The user-defined channel ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
        operation = client.delete_channel(name=name)
        response = operation.result(600)
        print("Deleted channel")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Delete 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")
    #
    def delete_channel project_id:, location:, channel_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
    
      # Delete the channel.
      operation = client.delete_channel name: name
    
      # 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 a success message.
      puts "Deleted channel"
    end

    Use o comando OPERATION_ID para verificar o estado da operação até receber "done":true no resultado.

    Elimine o ponto final de entrada

    Use o método projects.locations.inputs.delete para eliminar o ponto final de entrada.

    REST

    Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

    • PROJECT_NUMBER: o número do seu Google Cloud projeto. Este encontra-se no campo Número do projeto na página Definições do IAM
    • LOCATION: a localização onde o seu ponto final de entrada está localizado; use uma das regiões suportadas
      Mostrar localizações
      • us-central1
      • us-east1
      • us-east4
      • us-west1
      • us-west2
      • northamerica-northeast1
      • southamerica-east1
      • asia-east1
      • asia-east2
      • asia-south1
      • asia-northeast1
      • asia-southeast1
      • australia-southeast1
      • europe-north1
      • europe-west1
      • europe-west2
      • europe-west3
      • europe-west4
    • INPUT_ID: o identificador definido pelo utilizador para o ponto final de entrada

    Para enviar o seu pedido, expanda uma destas opções:

    Deve receber uma resposta JSON semelhante à seguinte:

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
        "createTime": CREATE_TIME,
        "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
        "verb": "delete",
        "requestedCancellation": false,
        "apiVersion": "v1"
      },
      "done": false
    }
    

    C#

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    using Google.Cloud.Video.LiveStream.V1;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;
    
    public class DeleteInputSample
    {
        public async Task DeleteInputAsync(
             string projectId, string locationId, string inputId)
        {
            // Create the client.
            LivestreamServiceClient client = LivestreamServiceClient.Create();
    
            DeleteInputRequest request = new DeleteInputRequest
            {
                InputName = InputName.FromProjectLocationInput(projectId, locationId, inputId)
            };
    
            // Make the request.
            Operation<Empty, OperationMetadata> response = await client.DeleteInputAsync(request);
    
            // Poll until the returned long-running operation is complete.
            await response.PollUntilCompletedAsync();
        }
    }

    Go

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	livestream "cloud.google.com/go/video/livestream/apiv1"
    	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
    )
    
    // deleteInput deletes a previously-created input endpoint.
    func deleteInput(w io.Writer, projectID, location, inputID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// inputID := "my-input"
    	ctx := context.Background()
    	client, err := livestream.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &livestreampb.DeleteInputRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
    	}
    
    	op, err := client.DeleteInput(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteInput: %w", err)
    	}
    	err = op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("Wait: %w", err)
    	}
    
    	fmt.Fprintf(w, "Deleted input")
    	return nil
    }
    

    Java

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import com.google.cloud.video.livestream.v1.DeleteInputRequest;
    import com.google.cloud.video.livestream.v1.InputName;
    import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class DeleteInput {
    
      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 inputId = "my-input-id";
    
        deleteInput(projectId, location, inputId);
      }
    
      public static void deleteInput(String projectId, String location, 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 deleteInputRequest =
            DeleteInputRequest.newBuilder()
                .setName(InputName.of(projectId, location, inputId).toString())
                .build();
        // First API call in a project can take up to 10 minutes.
        livestreamServiceClient.deleteInputAsync(deleteInputRequest).get(10, TimeUnit.MINUTES);
        System.out.println("Deleted input");
        livestreamServiceClient.close();
      }
    }

    Node.js

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // inputId = 'my-input';
    
    // Imports the Livestream library
    const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;
    
    // Instantiates a client
    const livestreamServiceClient = new LivestreamServiceClient();
    
    async function deleteInput() {
      // Construct request
      const request = {
        name: livestreamServiceClient.inputPath(projectId, location, inputId),
      };
    
      // Run request
      const [operation] = await livestreamServiceClient.deleteInput(request);
      await operation.promise();
      console.log('Deleted input');
    }
    
    deleteInput();

    PHP

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
    use Google\Cloud\Video\LiveStream\V1\DeleteInputRequest;
    
    /**
     * Deletes an input.
     *
     * @param string  $callingProjectId   The project ID to run the API call under
     * @param string  $location           The location of the input
     * @param string  $inputId            The ID of the input to be deleted
     */
    function delete_input(
        string $callingProjectId,
        string $location,
        string $inputId
    ): void {
        // Instantiate a client.
        $livestreamClient = new LivestreamServiceClient();
        $formattedName = $livestreamClient->inputName($callingProjectId, $location, $inputId);
    
        // Run the input deletion request. The response is a long-running operation ID.
        $request = (new DeleteInputRequest())
            ->setName($formattedName);
        $operationResponse = $livestreamClient->deleteInput($request);
        $operationResponse->pollUntilComplete();
        if ($operationResponse->operationSucceeded()) {
            // Print status
            printf('Deleted input %s' . PHP_EOL, $inputId);
        } else {
            $error = $operationResponse->getError();
            // handleError($error)
        }
    }

    Python

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    
    import argparse
    
    from google.cloud.video.live_stream_v1.services.livestream_service import (
        LivestreamServiceClient,
    )
    from google.protobuf import empty_pb2 as empty
    
    
    def delete_input(project_id: str, location: str, input_id: str) -> empty.Empty:
        """Deletes an input.
        Args:
            project_id: The GCP project ID.
            location: The location of the input.
            input_id: The user-defined input ID."""
    
        client = LivestreamServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/inputs/{input_id}"
        operation = client.delete_input(name=name)
        response = operation.result(600)
        print("Deleted input")
    
        return response
    
    

    Ruby

    Para saber como instalar e usar a biblioteca cliente da API Live Stream, consulte o artigo Bibliotecas cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby API Live Stream.

    Para se autenticar na API Live Stream, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

    require "google/cloud/video/live_stream"
    
    ##
    # Delete an input endpoint
    #
    # @param project_id [String] Your Google Cloud project (e.g. "my-project")
    # @param location [String] The location (e.g. "us-central1")
    # @param input_id [String] Your input name (e.g. "my-input")
    #
    def delete_input project_id:, location:, input_id:
      # Create a Live Stream client.
      client = Google::Cloud::Video::LiveStream.livestream_service
    
      # Build the resource name of the input.
      name = client.input_path project: project_id, location: location, input: input_id
    
      # Delete the input.
      operation = client.delete_input name: name
    
      # 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 a success message.
      puts "Deleted input"
    end

    Elimine o contentor do Cloud Storage

    Tenha em atenção que todos os ficheiros e pastas no contentor gerado pela API Live Stream são eliminados quando para o canal.

    1. Na Google Cloud consola, aceda à página do navegador do Cloud Storage.

      Aceda à página do navegador do armazenamento na nuvem

    2. Selecione a caixa de verificação junto ao grupo criado.

    3. Clique em Eliminar.

    4. Na janela de pop-up apresentada, clique em Eliminar para eliminar permanentemente o contentor e o respetivo conteúdo.

    Revogue as suas credenciais

    1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

      gcloud auth application-default revoke
    2. Optional: Revoke credentials from the gcloud CLI.

      gcloud auth revoke

    O que se segue?