Cómo crear una sesión en vivo

Crea una sesión en la que los anuncios se unen de forma dinámica durante las pausas publicitarias de una transmisión en vivo.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C#

Antes de probar esta muestra, sigue las instrucciones de configuración de C# que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de C# de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar esta muestra, sigue las instrucciones de configuración de Go que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Go de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar esta muestra, sigue las instrucciones de configuración de Java que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Java de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar esta muestra, sigue las instrucciones de configuración de Node.js que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Node.js de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar esta muestra, sigue las instrucciones de configuración de PHP que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de PHP de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar esta muestra, sigue las instrucciones de configuración de Python que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Python de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)

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 probar esta muestra, sigue las instrucciones de configuración de Ruby que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Ruby de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

¿Qué sigue?

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