Gerenciar uma sessão ao vivo

Com a API Video Stitcher, você cria uma sessão ao vivo sempre que inicia a reprodução de uma transmissão em que os anúncios são agrupados dinamicamente durante os intervalos. A resposta contém o URL de reprodução e a configuração da sessão ao vivo.

Esta página descreve como criar e gerenciar uma sessão ao vivo que não é ativada pelo Google Ad Manager. Para mais informações sobre esses tipos de sessões ao vivo, consulte Gerenciar uma sessão ao vivo ativada pelo Google Ad Manager.

Antes de começar

Criar uma sessão ao vivo

Para criar uma sessão ao vivo, use o método projects.locations.liveSessions.create.

Quando você cria uma sessão ao vivo, os seguintes campos são opcionais:

REST

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_NUMBER: o número do projeto do Google Cloud localizado no campo Número do projeto da página Configurações do IAM
  • LOCATION: o local em que a sessão será criada. Use uma das regiões com suporte.
    Mostrar locais
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • LIVE_CONFIG_ID: o identificador definido pelo usuário para a configuração ativa

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID",
  "playUri": "PLAY_URI",
  "liveConfig": "projects/PROJECT_NUMBER/locations/LOCATION/liveConfigs/LIVE_CONFIG_ID",
}

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 ver mais informações, consulte a documentação de referência da API C# da API Video Stitcher.

Para autenticar na 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 ver mais informações, consulte a documentação de referência da API Go da API Video Stitcher.

Para autenticar na 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 de Java no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para ver mais informações, consulte a documentação de referência da API Java da API Video Stitcher.

Para autenticar na 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 ver mais informações, consulte a documentação de referência da API Node.js da API Video Stitcher.

Para autenticar na 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 de PHP no Guia de início rápido da API Video Stitcher usando bibliotecas de cliente. Para ver mais informações, consulte a documentação de referência da API PHP da API Video Stitcher.

Para autenticar na 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 ver mais informações, consulte a documentação de referência da API Python da API Video Stitcher.

Para autenticar na 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 ver mais informações, consulte a documentação de referência da API Ruby da API Video Stitcher.

Para autenticar na 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 resposta é um objeto da sessão ao vivo. O playUri é o URL que o dispositivo cliente usa para reproduzir o stream combinado do anúncio para essa sessão ao vivo.

A API Video Stitcher gera um ID de sessão único para cada solicitação. A sessão expira quando o playUri não é solicitado nos últimos cinco minutos.

O anúncio precisa ser codificado antes de ser unido a uma sessão ao vivo. Quando você cria uma sessão para um vídeo com anúncios em vídeo, a API Video Stitcher determina se o anúncio já foi codificado em uma sessão anterior. A API só procura anúncios codificados criados por sessões associadas ao seu projeto do Google Cloud. Para mais informações sobre esse processo, consulte a Visão geral.

Se você estiver gerando uma sessão em nome dos dispositivos dos seus clientes, defina os seguintes parâmetros usando cabeçalhos HTTP:

Parâmetro Cabeçalho HTTP
CLIENT_IP x-forwarded-for
REFERRER_URL referer
USER_AGENT user-agent

É possível adicionar os seguintes cabeçalhos à solicitação curl anterior:

-H "x-forwarded-for: CLIENT_IP" \
-H "referer: REFERRER_URL" \
-H "user-agent: USER_AGENT" \

Se o cabeçalho x-forwarded-for não for fornecido, a API Video Stitcher usará o endereço IP do cliente em solicitações de metadados do anúncio. O endereço IP do cliente pode não corresponder ao IP dos dispositivos dos seus clientes se as sessões forem geradas em nome dos dispositivos deles.

Macros da tag de anúncio

Uma tag de anúncio pode conter macros, que podem produzir uma tag de anúncio diferente para cada sessão. As macros são indicadas por colchetes na tag de anúncio, conforme ilustrado pelo exemplo a seguir:

AD_TAG_URI&macro=[my-key]

O adTagUri é definido na configuração em tempo real.

Para substituir o valor na macro da tag de anúncio, forneça um mapeamento no campo adTagMacros. Por exemplo, se você quiser substituir a macro [my-key] pela string my-value, forneça o seguinte:

{
  ...
  "adTagMacros": {
    "my-key": "my-value"
  },
  ...
}

Quando a API Video Stitcher solicita os metadados do anúncio, ela usa a seguinte tag de anúncio:

AD_TAG_URI&macro=my-value

Receber uma sessão

Para acessar a sessão ao vivo, use o método projects.locations.liveSessions.get.

REST

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_NUMBER: o número do projeto do Google Cloud localizado no campo Número do projeto da página Configurações do IAM
  • LOCATION: o local em que a sessão será criada. Use uma das regiões com suporte.
    Mostrar locais
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • SESSION_ID: o identificador da sessão ao vivo.

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID",
  "playUri": "ad-stitched-live-stream-uri",
  "liveConfig": "projects/PROJECT_NUMBER/locations/LOCATION/liveConfigs/LIVE_CONFIG_ID",
}

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 ver mais informações, consulte a documentação de referência da API C# da API Video Stitcher.

Para autenticar na 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 GetLiveSessionSample
{
    public LiveSession GetLiveSession(
        string projectId, string location, string sessionId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetLiveSessionRequest request = new GetLiveSessionRequest
        {
            LiveSessionName = LiveSessionName.FromProjectLocationLiveSession(projectId, location, sessionId)
        };

        // Call the API.
        LiveSession session = client.GetLiveSession(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 ver mais informações, consulte a documentação de referência da API Go da API Video Stitcher.

Para autenticar na 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"
)

// getLiveSession gets a livestream session by ID.
func getLiveSession(w io.Writer, projectID, sessionID string) error {
	// projectID := "my-project-id"
	// sessionID := "123-456-789"
	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.GetLiveSessionRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/liveSessions/%s", projectID, location, sessionID),
	}
	// Gets the session.
	response, err := client.GetLiveSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetLiveSession: %w", err)
	}

	fmt.Fprintf(w, "Live session: %+v", response)
	return nil
}

Java

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

Para autenticar na 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.GetLiveSessionRequest;
import com.google.cloud.video.stitcher.v1.LiveSession;
import com.google.cloud.video.stitcher.v1.LiveSessionName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class GetLiveSession {

  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 sessionId = "my-session-id";

    getLiveSession(projectId, location, sessionId);
  }

  public static void getLiveSession(String projectId, String location, String sessionId)
      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()) {
      GetLiveSessionRequest getLiveSessionRequest =
          GetLiveSessionRequest.newBuilder()
              .setName(LiveSessionName.of(projectId, location, sessionId).toString())
              .build();

      LiveSession response = videoStitcherServiceClient.getLiveSession(getLiveSessionRequest);
      System.out.println("Live session: " + response.getName());
    }
  }
}

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 ver mais informações, consulte a documentação de referência da API Node.js da API Video Stitcher.

Para autenticar na 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';
// sessionId = 'my-session-id';

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

async function getLiveSession() {
  // Construct request
  const request = {
    name: stitcherClient.liveSessionPath(projectId, location, sessionId),
  };
  const [session] = await stitcherClient.getLiveSession(request);
  console.log(`Live session: ${session.name}`);
}

getLiveSession();

PHP

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

Para autenticar na 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\GetLiveSessionRequest;

/**
 * Gets a live session.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $sessionId            The ID of the session
 */
function get_live_session(
    string $callingProjectId,
    string $location,
    string $sessionId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->liveSessionName($callingProjectId, $location, $sessionId);
    $request = (new GetLiveSessionRequest())
        ->setName($formattedName);
    $session = $stitcherClient->getLiveSession($request);

    // Print results
    printf('Live session: %s' . PHP_EOL, $session->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 ver mais informações, consulte a documentação de referência da API Python da API Video Stitcher.

Para autenticar na 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 get_live_session(
    project_id: str, location: str, session_id: str
) -> stitcher_v1.types.LiveSession:
    """Gets a live session. Live sessions are ephemeral resources that expire
    after a few minutes.
    Args:
        project_id: The GCP project ID.
        location: The location of the session.
        session_id: The ID of the live session.

    Returns:
        The live session resource.
    """

    client = VideoStitcherServiceClient()

    name = client.live_session_path(project_id, location, session_id)
    response = client.get_live_session(name=name)
    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 ver mais informações, consulte a documentação de referência da API Ruby da API Video Stitcher.

Para autenticar na 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"

##
# Get a live 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 session_id [String] The live session ID (e.g. "my-live-session-id")
#
def get_live_session project_id:, location:, session_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the live session.
  name = client.live_session_path project: project_id, location: location,
                                  live_session: session_id

  # Get the live session.
  session = client.get_live_session name: name

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

Exemplo de playlist com anúncios

Confira a seguir um exemplo de playlist ao vivo de origem antes do agrupamento de anúncios:

#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:5
#EXTINF:10.010
segment_00005.ts
#EXTINF:10.010
segment_00006.ts
#EXT-X-DATERANGE:ID="2415919105",START-DATE="2021-06-22T08:32:00Z",DURATION=60,SCTE35-OUT=0xF...
#EXTINF:10.010
segment_00007.ts
#EXTINF:10.010
segment_00008.ts
#EXT-X-DATERANGE:ID="2415919105",START-DATE="2021-06-22T08:39:20Z",SCTE35-IN=0xF...
#EXTINF:10.010
segment_00009.ts

Confira a seguir um exemplo de playlist ao vivo de origem após o agrupamento de anúncios:

#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:5
#EXTINF:10.010
segment_00005.ts
#EXTINF:10.010
segment_00006.ts
#EXT-X-DISCONTINUITY
#EXTINF:6.000
https://ads.us-west1.cdn.videostitcher.goog/ad-1/seg-1.ts
#EXTINF:5.000
https://ads.us-west1.cdn.videostitcher.goog/ad-1/seg-2.ts
#EXT-X-DISCONTINUITY
#EXTINF:6.000
https://ads.us-west1.cdn.videostitcher.goog/ad-2/seg-1.ts
#EXTINF:5.000
https://ads.us-west1.cdn.videostitcher.goog/ad-2/seg-2.ts
#EXT-X-DISCONTINUITY
#EXTINF:10.010
segment_00009.ts

Processar rastreamento de anúncios do lado do cliente

Quando o rastreamento de anúncios do cliente está ativado, o player é responsável por acionar esses eventos. Os metadados do anúncio fornecidos pela API Video Stitcher incluem informações de rastreamento de anúncios e anúncios complementares. A API Video Stitcher analisa essas informações da resposta da tag de anúncio.

Extrair o URI de metadados do anúncio HLS do manifesto

Em um manifesto de reprodução de HLS, um AdMetadataURI é codificado no atributo X-VAST-META da tag #EXT-X-DATERANGE. A tag #EXT-X-DATERANGE pode ser encontrada antes do primeiro segmento unido de cada anúncio.

Confira a seguir um exemplo de tag de metadados com marcação de tempo HLS:

#EXT-X-DATERANGE:ID="id123",START-DATE=2014-03-05T11:15:00Z,DURATION=15,X-VAST-META="eyJBZE1ldGFkYXRhVXJpIjogImh0dHBzOi8vZXhhbXBsZS5jb20vdjFhbHBoYS9wcm9qZWN0cy8xMjMvbG9jYXRpb25zL3VzLWNlbnRyYWwxL2xpdmVTZXNzaW9ucy9hYmMzMjEvYWRNZXRhZGF0YS9pZDEyMyJ9"

O valor de um atributo X-VAST-META é uma string JSON codificada em base64. Após a decodificação, é possível extrair o AdMetadataURI do JSON.

O exemplo a seguir mostra o X-VAST-META decodificado:

{
  "AdMetadataUri": "https://example.com/v1/projects/123/locations/us-central1/liveSessions/abc321/adMetadata/id123"
}

Encontrar o URI de metadados do anúncio DASH no manifesto

Em um manifesto DASH, cada período de anúncio combinado contém um anúncio VAST, e o URI de metadados dele pode ser extraído da tag EventStream. AdMetadataURI é codificado no atributo messageData do elemento Event. Event é um elemento dentro da tag EventStream com um schemeIdUri de urn:videostitcher:admetadata:202008.

Veja a seguir um exemplo de tag de fluxo de eventos DASH:

<EventStream schemeIdUri="urn:videostitcher:admetadata:202008" timescale="1000">
  <Event duration="5000" messageData="eyJBZE1ldGFkYXRhVXJpIjogImh0dHBzOi8vZXhhbXBsZS5jb20vdjFhbHBoYS9wcm9qZWN0cy8xMjMvbG9jYXRpb25zL3VzLWNlbnRyYWwxL2xpdmVTZXNzaW9ucy9hYmMzMjEvYWRNZXRhZGF0YS9pZDEyMyJ9"></Event>
</EventStream>

Use base64 para decodificar o messageData para JSON.

O exemplo a seguir mostra o messageData decodificado:

{
  "AdMetadataUri": "https://example.com/v1/projects/123/locations/us-central1/liveSessions/abc321/adMetadata/id123"
}

Recuperar e processar eventos de rastreamento de anúncios

Depois de receber o AdMetadataURI, será possível buscar metadados de anúncios.

O exemplo a seguir mostra os metadados do anúncio:

{
  "activityEvents": [
    {
      "type": "PAUSE",
      "uri": "https://example.com/pause"
    }
  ],
  "progressiveEvents": [
    {
      "timeOffset": "0s",
      "events": [
        {
          "type": "IMPRESSION",
          "uri": "https://example.com/impression"
        },
        {
          "type": "START",
          "uri": "https://example.com/start"
        }
      ]
    },
    {
      "timeOffset": "2.500s",
      "events": [
        {
          "type": "FIRST_QUARTILE",
          "uri": "https://example.com/firstquartile"
        }
      ]
    }
  ],
  "adDuration": "10s"
}

No exemplo anterior, o cliente precisa fazer o seguinte:

  • Solicitar https://example.com/start no início do vídeo do anúncio
  • Solicitar https://example.com/impression no início do vídeo do anúncio
  • Solicitar https://example.com/pause sempre que o espectador pausar o vídeo do anúncio
  • Solicitar https://example.com/firstQuartile 2,5 segundos no vídeo do anúncio

Inspecionar sessões ao vivo

Esta seção descreve como inspecionar sessões ao vivo e os detalhes da tag de anúncio de uma determinada sessão ao vivo. Para mais detalhes, consulte a documentação da REST.

A API Video Stitcher envia solicitações para provedores de anúncios especificados nas tags de anúncio no corpo de uma solicitação de sessão ao vivo. Os metadados de solicitação e resposta para essas solicitações são salvos por 14 dias e podem ser acessados inspecionando a sessão ao vivo.

A API Video Stitcher compõe os detalhes da tag de anúncio usando o seguinte:

  • O URL da tag de anúncio solicitado em um determinado intervalo de anúncio (ou a tag de anúncio padrão, se nenhuma for especificada)
  • As macros da tag de anúncio configuradas da solicitação da sessão ao vivo
  • Metadados do usuário adicionais

Essas informações, junto com o corpo e os metadados da resposta, fornecem informações sobre o comportamento da API Video Stitcher.

Listar detalhes da tag de anúncio

Para listar os detalhes da tag de anúncio de uma sessão ao vivo, use o método projects.locations.liveSessions.liveAdTagDetails.list.

Considere a seguinte resposta para uma sessão ativa criada anteriormente (alguns campos são omitidos):

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID",
  ...
}

REST

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_NUMBER: o número do projeto do Google Cloud localizado no campo Número do projeto da página Configurações do IAM
  • LOCATION: o local da sua sessão. Use uma das regiões com suporte .
    Mostrar locais
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • SESSION_ID: o identificador da sessão ao vivo.

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "liveAdTagDetails" : [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID/liveAdTagDetails/LIVE_AD_TAG_DETAILS_ID",
      "adRequests": [
        {
          "uri": "REQUEST_URL",
          "requestMetadata": "AD_TAG_REQUEST_METADATA",
          "responseMetadata": "AD_TAG_RESPONSE_METADATA"
        }
      ]
    }
  ]
}

Copie a LIVE_AD_TAG_DETAILS_ID retornada. Ele é necessário para ver os detalhes de uma única tag de anúncio.

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 ver mais informações, consulte a documentação de referência da API C# da API Video Stitcher.

Para autenticar na 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.Api.Gax;
using Google.Cloud.Video.Stitcher.V1;

public class ListLiveAdTagDetailsSample
{
    public PagedEnumerable<ListLiveAdTagDetailsResponse, LiveAdTagDetail> ListLiveAdTagDetails(
        string projectId, string regionId, string sessionId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        ListLiveAdTagDetailsRequest request = new ListLiveAdTagDetailsRequest
        {
            ParentAsLiveSessionName = LiveSessionName.FromProjectLocationLiveSession(projectId, regionId, sessionId)
        };

        // Make the request.
        PagedEnumerable<ListLiveAdTagDetailsResponse, LiveAdTagDetail> response = client.ListLiveAdTagDetails(request);

        // Return the result.
        return response;
    }
}

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 ver mais informações, consulte a documentação de referência da API Go da API Video Stitcher.

Para autenticar na 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"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
	"google.golang.org/api/iterator"
)

// listLiveAdTagDetails lists the ad tag details for the specified live session.
func listLiveAdTagDetails(w io.Writer, projectID, sessionID string) error {
	// projectID := "my-project-id"
	// sessionID := "my-session-id"
	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 := &stitcherstreampb.ListLiveAdTagDetailsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/liveSessions/%s", projectID, location, sessionID),
	}

	it := client.ListLiveAdTagDetails(ctx, req)
	fmt.Fprintln(w, "Live ad tag details:")
	for {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("it.Next(): %w", err)
		}
		fmt.Fprintln(w, response.GetName())
	}
	return nil
}

Java

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

Para autenticar na 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.ListLiveAdTagDetailsRequest;
import com.google.cloud.video.stitcher.v1.LiveAdTagDetail;
import com.google.cloud.video.stitcher.v1.LiveSessionName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class ListLiveAdTagDetails {

  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 sessionId = "my-session-id";

    listLiveAdTagDetails(projectId, location, sessionId);
  }

  public static void listLiveAdTagDetails(String projectId, String location, String sessionId)
      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()) {
      ListLiveAdTagDetailsRequest listLiveAdTagDetailsRequest =
          ListLiveAdTagDetailsRequest.newBuilder()
              .setParent(LiveSessionName.of(projectId, location, sessionId).toString())
              .build();

      VideoStitcherServiceClient.ListLiveAdTagDetailsPagedResponse response =
          videoStitcherServiceClient.listLiveAdTagDetails(listLiveAdTagDetailsRequest);
      System.out.println("Live ad tag details:");

      for (LiveAdTagDetail adTagDetail : response.iterateAll()) {
        System.out.println(adTagDetail.toString());
      }
    }
  }
}

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 ver mais informações, consulte a documentação de referência da API Node.js da API Video Stitcher.

Para autenticar na 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';
// sessionId = 'my-session-id';

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

async function listLiveAdTagDetails() {
  // Construct request
  const request = {
    parent: stitcherClient.liveSessionPath(projectId, location, sessionId),
  };
  const iterable = await stitcherClient.listLiveAdTagDetailsAsync(request);
  console.log('Live ad tag details:');
  for await (const response of iterable) {
    console.log(response.name);
  }
}

listLiveAdTagDetails();

PHP

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

Para autenticar na 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\ListLiveAdTagDetailsRequest;

/**
 * Lists the ad tag details for the specified live session.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $sessionId            The ID of the session
 */
function list_live_ad_tag_details(
    string $callingProjectId,
    string $location,
    string $sessionId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->liveSessionName($callingProjectId, $location, $sessionId);
    $request = (new ListLiveAdTagDetailsRequest())
        ->setParent($formattedName);
    $response = $stitcherClient->listLiveAdTagDetails($request);

    // Print the ad tag details list.
    $adTagDetails = $response->iterateAllElements();
    print('Live ad tag details:' . PHP_EOL);
    foreach ($adTagDetails as $adTagDetail) {
        printf('%s' . PHP_EOL, $adTagDetail->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 ver mais informações, consulte a documentação de referência da API Python da API Video Stitcher.

Para autenticar na 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.stitcher_v1.services.video_stitcher_service import (
    pagers,
    VideoStitcherServiceClient,
)


def list_live_ad_tag_details(
    project_id: str, location: str, session_id: str
) -> pagers.ListLiveAdTagDetailsPager:
    """Lists the ad tag details for the specified live session.
    Args:
        project_id: The GCP project ID.
        location: The location of the session.
        session_id: The ID of the live session.

    Returns:
        An iterable object containing live ad tag details resources.
    """

    client = VideoStitcherServiceClient()

    parent = client.live_session_path(project_id, location, session_id)
    page_result = client.list_live_ad_tag_details(parent=parent)
    print("Live ad tag details:")
    for response in page_result:
        print(response)

    return page_result

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 ver mais informações, consulte a documentação de referência da API Ruby da API Video Stitcher.

Para autenticar na 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"

##
# List the ad tag details for a live session
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param session_id [String] The live session ID (e.g. "my-live-session-id")
#
def list_live_ad_tag_details project_id:, location:, session_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.live_session_path project: project_id, location: location,
                                    live_session: session_id

  # List all ad tag details for the live session.
  response = client.list_live_ad_tag_details parent: parent

  puts "Live ad tag details:"
  # Print out all live ad tag details.
  response.each do |live_ad_tag_detail|
    puts live_ad_tag_detail.name
  end
end

Mais detalhes da tag de anúncio

Para conferir os detalhes de uma única tag de anúncio em uma sessão ao vivo, use o método projects.locations.liveSessions.liveAdTagDetails.get.

O exemplo a seguir demonstra a visualização de um único detalhe de tag de anúncio para uma sessão ativa usando o nome de uma tag de anúncio retornada de uma solicitação anterior:

REST

Antes de usar os dados da solicitação, faça as substituições a seguir:

  • PROJECT_NUMBER: o número do projeto do Google Cloud localizado no campo Número do projeto da página Configurações do IAM
  • LOCATION: o local da sua sessão. Use uma das regiões com suporte .
    Mostrar locais
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • SESSION_ID: o identificador da sessão ao vivo.
  • LIVE_AD_TAG_DETAILS_ID: o ID dos detalhes da tag de anúncio ativa.

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID/liveAdTagDetails/LIVE_AD_TAG_DETAILS_ID",
  "adRequests": [
    {
      "uri": "REQUEST_URL",
      "requestMetadata": "AD_TAG_REQUEST_METADATA",
      "responseMetadata": "AD_TAG_RESPONSE_METADATA"
    }
  ]
}

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 ver mais informações, consulte a documentação de referência da API C# da API Video Stitcher.

Para autenticar na 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 GetLiveAdTagDetailSample
{
    public LiveAdTagDetail GetLiveAdTagDetail(
        string projectId, string location, string sessionId, string adTagDetailId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetLiveAdTagDetailRequest request = new GetLiveAdTagDetailRequest
        {
            LiveAdTagDetailName = LiveAdTagDetailName.FromProjectLocationLiveSessionLiveAdTagDetail(projectId, location, sessionId, adTagDetailId)
        };

        // Call the API.
        LiveAdTagDetail liveAdTagDetail = client.GetLiveAdTagDetail(request);

        // Return the result.
        return liveAdTagDetail;
    }
}

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 ver mais informações, consulte a documentação de referência da API Go da API Video Stitcher.

Para autenticar na 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"
	"encoding/json"
	"fmt"
	"io"

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

// getLiveAdTagDetail gets the specified ad tag detail for a live session.
func getLiveAdTagDetail(w io.Writer, projectID, sessionID, adTagDetailID string) error {
	// projectID := "my-project-id"
	// sessionID := "my-session-id"
	// adTagDetailID := "my-ad-tag-detail-id"
	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 := &stitcherstreampb.GetLiveAdTagDetailRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/liveSessions/%s/liveAdTagDetails/%s", projectID, location, sessionID, adTagDetailID),
	}
	// Gets the ad tag detail.
	response, err := client.GetLiveAdTagDetail(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetLiveAdTagDetail: %w", err)
	}
	b, err := json.MarshalIndent(response, "", " ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}
	fmt.Fprintf(w, "Live ad tag detail:\n%v", string(b))
	return nil
}

Java

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

Para autenticar na 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.GetLiveAdTagDetailRequest;
import com.google.cloud.video.stitcher.v1.LiveAdTagDetail;
import com.google.cloud.video.stitcher.v1.LiveAdTagDetailName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class GetLiveAdTagDetail {

  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 sessionId = "my-session-id";
    String adTagDetailId = "my-ad-tag-detail-id";

    getLiveAdTagDetail(projectId, location, sessionId, adTagDetailId);
  }

  public static void getLiveAdTagDetail(
      String projectId, String location, String sessionId, String adTagDetailId)
      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()) {
      GetLiveAdTagDetailRequest getLiveAdTagDetailRequest =
          GetLiveAdTagDetailRequest.newBuilder()
              .setName(
                  LiveAdTagDetailName.of(projectId, location, sessionId, adTagDetailId).toString())
              .build();

      LiveAdTagDetail response =
          videoStitcherServiceClient.getLiveAdTagDetail(getLiveAdTagDetailRequest);
      System.out.println("Live ad tag detail: " + response.getName());
    }
  }
}

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 ver mais informações, consulte a documentação de referência da API Node.js da API Video Stitcher.

Para autenticar na 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';
// sessionId = 'my-session-id';
// adTagDetailId = 'my-ad-tag-detail-id';

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

async function getLiveAdTagDetail() {
  // Construct request
  const request = {
    name: stitcherClient.liveAdTagDetailPath(
      projectId,
      location,
      sessionId,
      adTagDetailId
    ),
  };
  const [adTagDetail] = await stitcherClient.getLiveAdTagDetail(request);
  console.log(`Live ad tag detail: ${adTagDetail.name}`);
}

getLiveAdTagDetail();

PHP

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

Para autenticar na 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\GetLiveAdTagDetailRequest;

/**
 * Gets the specified ad tag detail for the live session.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $sessionId            The ID of the session
 * @param string $adTagDetailId        The ID of the ad tag detail
 */
function get_live_ad_tag_detail(
    string $callingProjectId,
    string $location,
    string $sessionId,
    string $adTagDetailId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->liveAdTagDetailName($callingProjectId, $location, $sessionId, $adTagDetailId);
    $request = (new GetLiveAdTagDetailRequest())
        ->setName($formattedName);
    $adTagDetail = $stitcherClient->getLiveAdTagDetail($request);

    // Print results
    printf('Live ad tag detail: %s' . PHP_EOL, $adTagDetail->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 ver mais informações, consulte a documentação de referência da API Python da API Video Stitcher.

Para autenticar na 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 get_live_ad_tag_detail(
    project_id: str, location: str, session_id: str, ad_tag_detail_id: str
) -> stitcher_v1.types.LiveAdTagDetail:
    """Gets the specified ad tag detail for a live session.
    Args:
        project_id: The GCP project ID.
        location: The location of the session.
        session_id: The ID of the live session.
        ad_tag_detail_id: The ID of the ad tag details.

    Returns:
        The live ad tag detail resource.
    """

    client = VideoStitcherServiceClient()

    name = client.live_ad_tag_detail_path(
        project_id, location, session_id, ad_tag_detail_id
    )
    response = client.get_live_ad_tag_detail(name=name)
    print(f"Live ad tag detail: {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 ver mais informações, consulte a documentação de referência da API Ruby da API Video Stitcher.

Para autenticar na 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"

##
# Get the specified ad tag detail for a live session
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param session_id [String] The live session ID (e.g. "my-live-session-id")
# @param ad_tag_detail_id [String] The ad tag detail ID (e.g. "my-ad-tag-id")
#
def get_live_ad_tag_detail project_id:, location:, session_id:,
                           ad_tag_detail_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the live ad tag detail.
  name = client.live_ad_tag_detail_path project: project_id, location: location,
                                        live_session: session_id,
                                        live_ad_tag_detail: ad_tag_detail_id

  # Get the live ad tag detail.
  ad_tag_detail = client.get_live_ad_tag_detail name: name

  # Print the live ad tag detail name.
  puts "Live ad tag detail: #{ad_tag_detail.name}"
end