MPEG-DASH 直播快速入门

本页介绍了如何使用 Live Stream API 的默认设置和 curl、PowerShell 或客户端库创建基本的 MPEG-DASH 直播作业。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 安装 Google Cloud CLI。
  3. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  4. 创建或选择 Google Cloud 项目

    • 创建 Google Cloud 项目:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替换为您要创建的 Google Cloud 项目的名称。

    • 选择您创建的 Google Cloud 项目:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替换为您的 Google Cloud 项目 名称。

  5. 确保您的 Google Cloud 项目已启用结算功能

  6. Enable the Live Stream API:

    gcloud services enable livestream.googleapis.com
  7. 为您的 Google 账号创建本地身份验证凭据:

    gcloud auth application-default login
  8. 向您的 Google 账号授予角色。对以下每个 IAM 角色运行以下命令一次: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID 替换为您的项目 ID。
    • EMAIL_ADDRESS 替换为您的电子邮件地址。
    • ROLE 替换为每个角色。
  9. 安装 Google Cloud CLI。
  10. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  11. 创建或选择 Google Cloud 项目

    • 创建 Google Cloud 项目:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替换为您要创建的 Google Cloud 项目的名称。

    • 选择您创建的 Google Cloud 项目:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替换为您的 Google Cloud 项目 名称。

  12. 确保您的 Google Cloud 项目已启用结算功能

  13. Enable the Live Stream API:

    gcloud services enable livestream.googleapis.com
  14. 为您的 Google 账号创建本地身份验证凭据:

    gcloud auth application-default login
  15. 向您的 Google 账号授予角色。对以下每个 IAM 角色运行以下命令一次: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID 替换为您的项目 ID。
    • EMAIL_ADDRESS 替换为您的电子邮件地址。
    • ROLE 替换为每个角色。

创建 Cloud Storage 存储桶

创建 Cloud Storage 存储桶以保存直播清单和片段文件。

Google Cloud 控制台

  1. 在 Google Cloud 控制台中,进入 Cloud Storage 存储桶页面。

    进入“存储桶”页面

  2. 点击创建存储分区
  3. 创建存储分区页面上,输入您的存储分区信息。要转到下一步,请点击继续
    • 指定存储分区的名称中,输入符合存储分区命名要求的名称。
    • 对于选择数据存储位置,执行以下操作:
      • 选择位置类型选项。
      • 选择位置选项。
    • 对于为数据选择一个默认存储类别,选择以下项: Standard
    • 对于选择如何控制对象的访问权限,请选择访问权限控制选项。
    • 对于高级设置(可选),请指定加密方法保留政策存储分区标签
  4. 点击创建

命令行

    创建 Cloud Storage 存储分区:
    gcloud storage buckets create gs://BUCKET_NAME
    BUCKET_NAME 替换为符合存储桶名称要求的存储桶名称。

安装编码器

要使用该 API,您需要一个编码器来生成供 API 处理的输入流。

安装 ffmpeg,因为本页介绍了如何使用 ffmpeg 生成输入流。您可以使用以下命令在 Cloud Shell 中安装此组件。

sudo apt install ffmpeg

创建输入端点

如需开始直播,您必须先使用 projects.locations.inputs.create 方法创建输入端点。您需要将输入流发送到此端点。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:要在其中创建输入端点的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID:用户定义的新输入端点标识符,要创建的新输入端点(您将输入流发送到此端点)。此值必须为 1-63 个字符,以 [a-z0-9] 开头和结尾,可在字符之间包含短划线 (-)。例如 my-input

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

复制返回的 OPERATION_ID 以便在下一部分中使用。

查看结果

使用 projects.locations.operations.get 方法检查是否已创建输入端点。如果响应包含 "done: false",请重复该命令,直到响应包含 "done: true"。在区域中创建第一个输入端点最多可能需要 10 分钟。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:输入端点所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • OPERATION_ID:操作的标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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"
  }
}

找到 uri 字段并复制返回的 INPUT_STREAM_URI,以便稍后在发送输入流部分使用。

创建频道

如需将输入流转码为输出流,您需要创建频道资源。

如需创建渠道,请使用 projects.locations.channels.create 方法。以下示例会创建一个生成 MPEG-DASH 直播流的频道,该直播由单个高清 (1280x720) 转写内容组成。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:要在其中创建频道的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符;此值必须为 1-63 个字符,以 [a-z0-9] 开头和结尾,并且可以在字符之间包含短划线 (-)
  • INPUT_ID:用户定义的输入端点标识符
  • BUCKET_NAME:您为了保存直播清单和片段文件而创建的 Cloud Storage 存储桶的名称

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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
}

订阅频道

您可以使用新的操作 ID 查看频道创建操作的结果

创建频道后,使用 projects.locations.channels.get 方法查询频道状态。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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": [
    {
      "fileName": "main.mpd",
      "type": "DASH",
      "muxStreams": [
        "mux_video",
        "mux_audio"
      ],
      "maxSegmentCount": 5,
      "segmentKeepDuration": "60s"
    }
  ],
  "streamingState": "STOPPED"
}

C#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

完整响应包含以下字段。(上面的某些代码示例仅返回响应中的特定字段,但可以修改为返回完整响应。)

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

此响应表示您现在可以启动频道了。

创建频道

使用 projects.locations.channels.start 方法启动渠道。通道必须先启动,然后才能接受输入流或生成输出流。

启动区域中的第一个频道大约需要 10 分钟。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

发送输入流

如需确定频道是否已开始,请像之前一样获取频道信息。响应应包含以下内容:

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

现在频道已准备就绪,请将测试输入流发送到输入端点,以生成直播。

打开一个新终端窗口。使用检查结果部分中的 INPUT_STREAM_URI 运行以下命令:

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

检查频道是否正在直播

如需检查直播操作的状态,请像之前一样获取频道信息。响应应包含以下内容:

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

验证 Cloud Storage 存储桶中的内容

打开 Cloud Storage 存储桶。确认它包含以下文件和目录:

  • main.mpd
  • mux_audio/
    • 多个 segment-segment-number.m4s 文件
    • 单个 segment-initialization_segment_0000000000.m4s 文件
  • mux_video/
    • 多个 segment-segment-number.m4s 文件
    • 单个 segment-initialization_segment_0000000000.m4s 文件

播放生成的直播

如需在 Shaka Player 中播放生成的媒体文件,请完成以下步骤:

  1. 请将 Cloud Storage 存储桶设为可公开读取
  2. 如需在 Cloud Storage 存储桶上启用跨域资源共享 (CORS),请执行以下操作:
    1. 创建一个包含以下代码的 JSON 文件:
      [
        {
          "origin": ["https://shaka-player-demo.appspot.com/"],
          "responseHeader": ["Content-Type", "Range"],
          "method": ["GET", "HEAD"],
          "maxAgeSeconds": 3600
        }
      ]
    2. JSON_FILE_NAME 替换为您在上一步中创建的 JSON 文件的名称,然后运行以下命令:
      gsutil cors set JSON_FILE_NAME.json gs://BUCKET_NAME
  3. 在 Cloud Storage 存储桶中,找到生成的 main.mpd 文件。在该文件的公开访问权限列中,点击复制网址
  4. 导航到在线直播播放器 Shaka Player
  5. 点击顶部导航栏中的自定义内容
  6. 点击 + 按钮。
  7. 将文件的公开网址粘贴到清单网址框中。

  8. 名称框中输入一个名称。

  9. 点击保存

  10. 点击播放

您应该会看到作为直播呈现的测试流。

测试图案视频

向直播添加广告插播时间点标记

使用 projects.locations.channels.events.create 方法向直播添加广告插播时间点标记。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符
  • EVENT_ID:用户定义的事件标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

验证广告插播时间点标记是否存在

在直播中插入广告标记后,标记为 <SpliceInfoSection> 的事件将在指定的广告时长(100 秒)内显示在 DASH 清单中。

运行以下命令以查看生成的 DASH 清单的内容:

gsutil cat gs://BUCKET_NAME/main.mpd

您可能需要运行 gsutil cat 命令多次,直到显示 <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>

清理

为避免因本页中使用的资源导致您的 Google Cloud 账号产生费用,请按照以下步骤操作。

停止频道

使用 projects.locations.channels.stop 方法停止渠道。你必须先停止该频道,然后才能将其删除。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

使用 OPERATION_ID 检查操作状态,直到结果中获得 "done":true

停止输入流

如果您使用 ffmpeg 发送输入流,则在您停止通道后,连接会自动断开。

如果您使用其他具有重试机制的编码器,则可能需要手动停止输入流。

删除活动

使用 projects.locations.channels.events.delete 方法删除广告插播时间点事件。您必须先删除频道事件,然后才能删除频道。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符
  • EVENT_ID:用户定义的事件标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{}

C#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

删除频道

使用 projects.locations.channels.delete 方法删除频道。您必须先删除渠道,然后才能删除该渠道使用的输入端点。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:您的频道所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID:用户定义的频道标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

使用 OPERATION_ID 检查操作状态,直到结果中获得 "done":true

删除输入端点

使用 projects.locations.inputs.delete 方法删除输入端点。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号;位于 IAM 设置页面上的项目编号字段中
  • LOCATION:输入端点所在的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID:用户定义的输入端点标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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#

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API C# API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Go API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Java API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Node.js API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API PHP API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Python API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

如需了解如何安装和使用 Live Stream API 客户端库,请参阅 Live Stream API 客户端库。 如需了解详情,请参阅 Live Stream API Ruby API 参考文档

如需向 Live Stream API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

删除 Cloud Storage 存储桶

请注意,停止频道后,系统会删除由 Live Stream API 生成的存储桶中的所有文件和文件夹。

  1. 在 Google Cloud 控制台中,前往“Cloud Storage 浏览器”页面。

    转到“Cloud Storage 浏览器”页面

  2. 选中所创建存储桶旁边的复选框。

  3. 点击删除

  4. 在显示的弹出式窗口中,点击删除以永久删除存储桶及其内容。

撤消您的凭据

  1. 可选:撤消您创建的身份验证凭据,并删除本地凭据文件。

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

    gcloud auth revoke

后续步骤