Criar um endpoint de entrada

Crie um endpoint para onde o codificador envia o stream de entrada. Você pode usar o endpoint de entrada para especificar configurações para o stream, como resolução, tipo de entrada e corte de vídeo.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C#

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

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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 de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby da API Live Stream.

Para autenticar a API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar 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

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte o navegador de amostra do Google Cloud.