Criar uma sessão ao vivo

Crie uma sessão ao vivo em que os anúncios são agrupados dinamicamente durante os intervalos de uma transmissão ao vivo.

Mais informações

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

Exemplo de código

C#

Antes de testar esta amostra, siga as instruções de configuração de C# no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API C# da API Video Stitcher.

Para autenticar a API Video Stitcher, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using Google.Cloud.Video.Stitcher.V1;

public class CreateLiveSessionSample
{
    public LiveSession CreateLiveSession(
        string projectId, string location, string liveConfigId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateLiveSessionRequest request = new CreateLiveSessionRequest
        {
            Parent = $"projects/{projectId}/locations/{location}",
            LiveSession = new LiveSession
            {
                LiveConfig = LiveConfigName.FormatProjectLocationLiveConfig(projectId, location, liveConfigId)
            }
        };

        // Call the API.
        LiveSession session = client.CreateLiveSession(request);

        // Return the result.
        return session;
    }
}

Go

Antes de testar esta amostra, siga as instruções de configuração de Go no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API Go da API Video Stitcher.

Para autenticar a API Video Stitcher, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	"cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createLiveSession creates a livestream session in which to insert ads.
// Live sessions are ephemeral resources that expire after a few minutes.
func createLiveSession(w io.Writer, projectID, liveConfigID string) error {
	// projectID := "my-project-id"
	// liveConfigID := "my-live-config"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherpb.CreateLiveSessionRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		LiveSession: &stitcherpb.LiveSession{
			LiveConfig: fmt.Sprintf("projects/%s/locations/%s/liveConfigs/%s", projectID, location, liveConfigID),
		},
	}
	// Creates the live session.
	response, err := client.CreateLiveSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateLiveSession: %w", err)
	}

	fmt.Fprintf(w, "Live session: %v\n", response.GetName())
	fmt.Fprintf(w, "Play URI: %v", response.GetPlayUri())
	return nil
}

Java

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API Java da API Video Stitcher.

Para autenticar a API Video Stitcher, 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.stitcher.v1.CreateLiveSessionRequest;
import com.google.cloud.video.stitcher.v1.LiveConfigName;
import com.google.cloud.video.stitcher.v1.LiveSession;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class CreateLiveSession {

  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 liveConfigId = "my-live-config-id";

    createLiveSession(projectId, location, liveConfigId);
  }

  public static void createLiveSession(String projectId, String location, String liveConfigId)
      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 (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CreateLiveSessionRequest createLiveSessionRequest =
          CreateLiveSessionRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setLiveSession(
                  LiveSession.newBuilder()
                      .setLiveConfig(LiveConfigName.format(projectId, location, liveConfigId)))
              .build();

      LiveSession response = videoStitcherServiceClient.createLiveSession(createLiveSessionRequest);
      System.out.println("Created live session: " + response.getName());
      System.out.println("Play URI: " + response.getPlayUri());
    }
  }
}

Node.js

Antes de testar esta amostra, siga as instruções de configuração de Node.js no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API Node.js da API Video Stitcher.

Para autenticar a API Video Stitcher, 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';
// liveConfigId = 'my-live-config-id';

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

async function createLiveSession() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    liveSession: {
      liveConfig: stitcherClient.liveConfigPath(
        projectId,
        location,
        liveConfigId
      ),
    },
  };

  const [session] = await stitcherClient.createLiveSession(request);
  console.log(`Live session: ${session.name}`);
  console.log(`Play URI: ${session.playUri}`);
}

createLiveSession();

PHP

Antes de testar esta amostra, siga as instruções de configuração do PHP no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API PHP da API Video Stitcher.

Para autenticar a API Video Stitcher, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateLiveSessionRequest;
use Google\Cloud\Video\Stitcher\V1\LiveSession;

/**
 * Creates a live session. Live sessions are ephemeral resources that expire
 * after a few minutes.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $liveConfigId         The live config ID to use to create the
 *                                     live session
 */
function create_live_session(
    string $callingProjectId,
    string $location,
    string $liveConfigId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $liveConfig = $stitcherClient->liveConfigName($callingProjectId, $location, $liveConfigId);
    $liveSession = new LiveSession();
    $liveSession->setLiveConfig($liveConfig);

    // Run live session creation request
    $request = (new CreateLiveSessionRequest())
        ->setParent($parent)
        ->setLiveSession($liveSession);
    $response = $stitcherClient->createLiveSession($request);

    // Print results
    printf('Live session: %s' . PHP_EOL, $response->getName());
}

Python

Antes de testar esta amostra, siga as instruções de configuração de Python no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API Python da API Video Stitcher.

Para autenticar a API Video Stitcher, 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 stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)

def create_live_session(
    project_id: str, location: str, live_config_id: str
) -> stitcher_v1.types.LiveSession:
    """Creates a live session. Live sessions are ephemeral resources that expire
    after a few minutes.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the session.
        live_config_id: The user-defined live config ID.

    Returns:
        The live session resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    live_config = (
        f"projects/{project_id}/locations/{location}/liveConfigs/{live_config_id}"
    )

    live_session = stitcher_v1.types.LiveSession(live_config=live_config)

    response = client.create_live_session(parent=parent, live_session=live_session)
    print(f"Live session: {response.name}")
    return response

Ruby

Antes de testar esta amostra, siga as instruções de configuração de Ruby no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para saber mais, consulte a documentação de referência da API Ruby da API Video Stitcher.

Para autenticar a API Video Stitcher, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

require "google/cloud/video/stitcher"

##
# Create a live stream session. Live sessions are ephemeral resources
# that expire after a few minutes.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param live_config_id [String] Your live config name (e.g. "my-live-config")
#
def create_live_session project_id:, location:, live_config_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  # Build the resource name of the live config.
  live_config_name = client.live_config_path project: project_id,
                                             location: location,
                                             live_config: live_config_id

  # Set the session fields.
  new_live_session = {
    live_config: live_config_name
  }

  response = client.create_live_session parent: parent,
                                        live_session: new_live_session

  # Print the live session name.
  puts "Live session: #{response.name}"
end

A seguir

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