Create and manage channels

This page shows you how to create and manage Live Stream API channels. A channel resource represents the processor that does a user-defined "streaming" operation. The streaming operation includes getting an input stream through an input endpoint, transcoding the input stream into multiple renditions, and publishing output live streams in certain formats in the specified location.

Set up your GCP project and authentication

Prerequisites

Create a channel

To create a channel, use the projects.locations.channels.create method. The following samples create a channel that generates an HLS live stream. The live stream consists of a single, high-definition (1280x720) rendition.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location in which to create the channel; use one of the supported regions:
    • 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: a user-defined identifier for the channel to create; this value must be 1-63 characters, begin and end with [a-z0-9], and can contain dashes (-) between characters
  • INPUT_ID: the user-defined identifier for the input endpoint
  • BUCKET_NAME: the name of the Cloud Storage bucket you created to hold the live stream manifest and segment files

Request JSON body:

{
  "inputAttachments": [
    {
      "key": "my-input",
      "input": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID"
    }
  ],
  "output": {
    "uri": "gs://BUCKET_NAME"
  },
  "elementaryStreams": [
    {
      "key": "es_video",
      "videoStream": {
        "h264": {
          "profile": "high",
          "widthPixels": 1280,
          "heightPixels": 720,
          "bitrateBps": 3000000,
          "frameRate": 30
        }
      }
    },
    {
      "key": "es_audio",
      "audioStream": {
        "codec": "aac",
        "channelCount": 2,
        "bitrateBps": 160000
      }
    }
  ],
  "muxStreams": [
    {
      "key": "mux_video_ts",
      "container": "ts",
      "elementaryStreams": ["es_video", "es_audio"],
      "segmentSettings": { "segmentDuration": "2s" }
    }
  ],
  "manifests": [
    {
      "fileName": "main.m3u8",
      "type": "HLS",
      "muxStreams": [
        "mux_video_ts"
      ],
      "maxSegmentCount": 5
    }
  ]
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	"github.com/golang/protobuf/ptypes/duration"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// createChannel creates a channel.
func createChannel(w io.Writer, projectID, location, channelID, inputID, outputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// inputID := "my-input"
	// outputURI := "gs://my-bucket/my-output-folder/"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	req := &livestreampb.CreateChannelRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ChannelId: channelID,
		Channel: &livestreampb.Channel{
			InputAttachments: []*livestreampb.InputAttachment{
				{
					Key:   "my-input",
					Input: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
				},
			},
			Output: &livestreampb.Channel_Output{
				Uri: outputURI,
			},
			ElementaryStreams: []*livestreampb.ElementaryStream{
				{
					Key: "es_video",
					ElementaryStream: &livestreampb.ElementaryStream_VideoStream{
						VideoStream: &livestreampb.VideoStream{
							CodecSettings: &livestreampb.VideoStream_H264{
								H264: &livestreampb.VideoStream_H264CodecSettings{
									Profile:      "high",
									BitrateBps:   3000000,
									FrameRate:    30,
									HeightPixels: 720,
									WidthPixels:  1280,
								},
							},
						},
					},
				},
				{
					Key: "es_audio",
					ElementaryStream: &livestreampb.ElementaryStream_AudioStream{
						AudioStream: &livestreampb.AudioStream{
							Codec:        "aac",
							ChannelCount: 2,
							BitrateBps:   160000,
						},
					},
				},
			},
			MuxStreams: []*livestreampb.MuxStream{
				{
					Key:               "mux_video",
					ElementaryStreams: []string{"es_video"},
					SegmentSettings: &livestreampb.SegmentSettings{
						SegmentDuration: &duration.Duration{
							Seconds: 2,
						},
					},
				},
				{
					Key:               "mux_audio",
					ElementaryStreams: []string{"es_audio"},
					SegmentSettings: &livestreampb.SegmentSettings{
						SegmentDuration: &duration.Duration{
							Seconds: 2,
						},
					},
				},
			},
			Manifests: []*livestreampb.Manifest{
				{
					FileName:        "manifest.m3u8",
					Type:            livestreampb.Manifest_HLS,
					MuxStreams:      []string{"mux_video", "mux_audio"},
					MaxSegmentCount: 5,
				},
			},
		},
	}
	// Creates the channel.
	op, err := client.CreateChannel(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateChannel: %v", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Channel: %v", response.Name)
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


import com.google.cloud.video.livestream.v1.AudioStream;
import com.google.cloud.video.livestream.v1.Channel;
import com.google.cloud.video.livestream.v1.Channel.Output;
import com.google.cloud.video.livestream.v1.CreateChannelRequest;
import com.google.cloud.video.livestream.v1.ElementaryStream;
import com.google.cloud.video.livestream.v1.InputAttachment;
import com.google.cloud.video.livestream.v1.InputName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.LocationName;
import com.google.cloud.video.livestream.v1.Manifest;
import com.google.cloud.video.livestream.v1.Manifest.ManifestType;
import com.google.cloud.video.livestream.v1.MuxStream;
import com.google.cloud.video.livestream.v1.SegmentSettings;
import com.google.cloud.video.livestream.v1.VideoStream;
import com.google.cloud.video.livestream.v1.VideoStream.H264CodecSettings;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateChannel {

  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 inputId = "my-input-id";
    String outputUri = "gs://my-bucket/my-output-folder/";

    createChannel(projectId, location, channelId, inputId, outputUri);
  }

  public static void createChannel(
      String projectId, String location, String channelId, String inputId, String outputUri)
      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.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      VideoStream videoStream =
          VideoStream.newBuilder()
              .setH264(
                  H264CodecSettings.newBuilder()
                      .setProfile("high")
                      .setBitrateBps(3000000)
                      .setFrameRate(30)
                      .setHeightPixels(720)
                      .setWidthPixels(1280))
              .build();

      AudioStream audioStream =
          AudioStream.newBuilder().setCodec("aac").setChannelCount(2).setBitrateBps(160000).build();

      var createChannelRequest =
          CreateChannelRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setChannelId(channelId)
              .setChannel(
                  Channel.newBuilder()
                      .addInputAttachments(
                          0,
                          InputAttachment.newBuilder()
                              .setKey("my-input")
                              .setInput(InputName.of(projectId, location, inputId).toString())
                              .build())
                      .setOutput(Output.newBuilder().setUri(outputUri).build())
                      .addElementaryStreams(
                          ElementaryStream.newBuilder()
                              .setKey("es_video")
                              .setVideoStream(videoStream))
                      .addElementaryStreams(
                          ElementaryStream.newBuilder()
                              .setKey("es_audio")
                              .setAudioStream(audioStream))
                      .addMuxStreams(
                          MuxStream.newBuilder()
                              .setKey("mux_video")
                              .addElementaryStreams("es_video")
                              .setSegmentSettings(
                                  SegmentSettings.newBuilder()
                                      .setSegmentDuration(
                                          Duration.newBuilder().setSeconds(2).build())
                                      .build())
                              .build())
                      .addMuxStreams(
                          MuxStream.newBuilder()
                              .setKey("mux_audio")
                              .addElementaryStreams("es_audio")
                              .setSegmentSettings(
                                  SegmentSettings.newBuilder()
                                      .setSegmentDuration(
                                          Duration.newBuilder().setSeconds(2).build())
                                      .build())
                              .build())
                      .addManifests(
                          Manifest.newBuilder()
                              .setFileName("manifest.m3u8")
                              .setType(ManifestType.HLS)
                              .addMuxStreams("mux_video")
                              .addMuxStreams("mux_audio")
                              .setMaxSegmentCount(5)
                              .build()))
              .build();

      Channel result =
          livestreamServiceClient.createChannelAsync(createChannelRequest).get(1, TimeUnit.MINUTES);
      System.out.println("Channel: " + result.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// channelId = 'my-channel';
// inputId = 'my-input';
// outputUri = 'gs://my-bucket/my-output-folder/';

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function createChannel() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.locationPath(projectId, location),
    channelId: channelId,
    channel: {
      inputAttachments: [
        {
          key: 'my-input',
          input: livestreamServiceClient.inputPath(
            projectId,
            location,
            inputId
          ),
        },
      ],
      output: {
        uri: outputUri,
      },
      elementaryStreams: [
        {
          key: 'es_video',
          videoStream: {
            h264: {
              profile: 'high',
              heightPixels: 720,
              widthPixels: 1280,
              bitrateBps: 3000000,
              frameRate: 30,
            },
          },
        },
        {
          key: 'es_audio',
          audioStream: {
            codec: 'aac',
            channelCount: 2,
            bitrateBps: 160000,
          },
        },
      ],
      muxStreams: [
        {
          key: 'mux_video',
          elementaryStreams: ['es_video'],
          segmentSettings: {
            seconds: 2,
          },
        },
        {
          key: 'mux_audio',
          elementaryStreams: ['es_audio'],
          segmentSettings: {
            seconds: 2,
          },
        },
      ],
      manifests: [
        {
          fileName: 'manifest.m3u8',
          type: 'HLS',
          muxStreams: ['mux_video', 'mux_audio'],
          maxSegmentCount: 5,
        },
      ],
    },
  };

  // Run request
  const [operation] = await livestreamServiceClient.createChannel(request);
  const response = await operation.promise();
  const [channel] = response;
  console.log(`Channel: ${channel.name}`);
}

createChannel();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


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(
    project_id: str, location: str, channel_id: str, input_id: str, output_uri: str
) -> str:
    """Creates a channel.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the channel.
        channel_id: The user-defined channel ID.
        input_id: The user-defined input ID.
        output_uri: Uri of the channel output folder in a Cloud Storage bucket."""

    client = LivestreamServiceClient()
    parent = f"projects/{project_id}/locations/{location}"
    input = f"projects/{project_id}/locations/{location}/inputs/{input_id}"
    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"

    channel = live_stream_v1.types.Channel(
        name=name,
        input_attachments=[
            live_stream_v1.types.InputAttachment(
                key="my-input",
                input=input,
            ),
        ],
        output=live_stream_v1.types.Channel.Output(
            uri=output_uri,
        ),
        elementary_streams=[
            live_stream_v1.types.ElementaryStream(
                key="es_video",
                video_stream=live_stream_v1.types.VideoStream(
                    h264=live_stream_v1.types.VideoStream.H264CodecSettings(
                        profile="high",
                        width_pixels=1280,
                        height_pixels=720,
                        bitrate_bps=3000000,
                        frame_rate=30,
                    ),
                ),
            ),
            live_stream_v1.types.ElementaryStream(
                key="es_audio",
                audio_stream=live_stream_v1.types.AudioStream(
                    codec="aac", channel_count=2, bitrate_bps=160000
                ),
            ),
        ],
        mux_streams=[
            live_stream_v1.types.MuxStream(
                key="mux_video",
                elementary_streams=["es_video"],
                segment_settings=live_stream_v1.types.SegmentSettings(
                    segment_duration=duration.Duration(
                        seconds=2,
                    ),
                ),
            ),
            live_stream_v1.types.MuxStream(
                key="mux_audio",
                elementary_streams=["es_audio"],
                segment_settings=live_stream_v1.types.SegmentSettings(
                    segment_duration=duration.Duration(
                        seconds=2,
                    ),
                ),
            ),
        ],
        manifests=[
            live_stream_v1.types.Manifest(
                file_name="manifest.m3u8",
                type_="HLS",
                mux_streams=["mux_video", "mux_audio"],
                max_segment_count=5,
            ),
        ],
    )
    operation = client.create_channel(
        parent=parent, channel=channel, channel_id=channel_id
    )
    response = operation.result(60)
    print(f"Channel: {response.name}")

    return response

Get channel details

To get the details of the channel, use the projects.locations.channels.get method.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location where your channel is located; use one of the supported regions:
    • 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: a user-defined identifier for the channel

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "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_ts",
      "container": "ts",
      "elementaryStreams": ["es_video", "es_audio"],
      "segmentSettings": { "segmentDuration": "2s" }
    }
  ],
  "manifests": [
    {
      "fileName": "main.m3u8",
      "type": "HLS",
      "muxStreams": [
        "mux_video_ts",
      ],
      "maxSegmentCount": 5,
      "segmentKeepDuration": "60s"
    }
  ],
  "streamingState": "STOPPED"
}

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// 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: %v", 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: %v", err)
	}

	fmt.Fprintf(w, "Channel: %v", response.Name)
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background 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

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * 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();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)


def get_channel(project_id: str, location: str, channel_id: str) -> str:
    """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

Update a channel

To update a channel, use the projects.locations.channels.patch method.

The following example updates the output URI and manifest filename and type. Not all fields can be updated; see the list of supported fields.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location in which to create the channel; use one of the supported regions:
    • 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: a user-defined identifier for the channel to create; this value should be 1-63 characters and valid characters are in the regular expression [a-z][0-9]-
  • INPUT_ID: the user-defined identifier for the input endpoint
  • BUCKET_NAME: the name of the Cloud Storage bucket you created

Request JSON body:

{
  "output": {
    "uri": "gs://BUCKET_NAME"
  },
  "manifests": [
    {
      "fileName": "manifest.m3u8",
      "type": "HLS",
      "muxStreams": [
        "mux_video",
        "mux_audio"
      ],
      "maxSegmentCount": 5
    }
  ]
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "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": "update",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateChannel updates an existing channel with a different input.
func updateChannel(w io.Writer, projectID, location, channelID, inputID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// inputID := "my-updated-input"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	req := &livestreampb.UpdateChannelRequest{
		Channel: &livestreampb.Channel{
			Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
			InputAttachments: []*livestreampb.InputAttachment{
				{
					Key:   "updated-input",
					Input: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
				},
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"input_attachments",
			},
		},
	}
	// Updates the input.
	op, err := client.UpdateChannel(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateChannel: %v", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Updated channel: %v", response.Name)
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


import com.google.cloud.video.livestream.v1.Channel;
import com.google.cloud.video.livestream.v1.ChannelName;
import com.google.cloud.video.livestream.v1.InputAttachment;
import com.google.cloud.video.livestream.v1.InputName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.UpdateChannelRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateChannel {

  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 inputId = "my-input-id";

    updateChannel(projectId, location, channelId, inputId);
  }

  public static void updateChannel(
      String projectId, String location, String channelId, 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.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var updateChannelRequest =
          UpdateChannelRequest.newBuilder()
              .setChannel(
                  Channel.newBuilder()
                      .setName(ChannelName.of(projectId, location, channelId).toString())
                      .addInputAttachments(
                          0,
                          InputAttachment.newBuilder()
                              .setKey("updated-input")
                              .setInput(InputName.of(projectId, location, inputId).toString())
                              .build()))
              .setUpdateMask(FieldMask.newBuilder().addPaths("input_attachments").build())
              .build();

      Channel result =
          livestreamServiceClient.updateChannelAsync(updateChannelRequest).get(1, TimeUnit.MINUTES);
      System.out.println("Updated channel: " + result.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// channelId = 'my-channel';
// inputId = 'my-input';

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function updateChannel() {
  // Construct request
  const request = {
    channel: {
      name: livestreamServiceClient.channelPath(
        projectId,
        location,
        channelId
      ),
      inputAttachments: [
        {
          key: 'updated-input',
          input: livestreamServiceClient.inputPath(
            projectId,
            location,
            inputId
          ),
        },
      ],
    },
    updateMask: {
      paths: ['input_attachments'],
    },
  };

  // Run request
  const [operation] = await livestreamServiceClient.updateChannel(request);
  const response = await operation.promise();
  const [channel] = response;
  console.log(`Updated channel: ${channel.name}`);
}

updateChannel();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


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 field_mask_pb2 as field_mask


def update_channel(
    project_id: str, location: str, channel_id: str, input_id: str
) -> str:
    """Updates a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID.
        input_id: The user-defined input ID for the new input."""

    client = LivestreamServiceClient()
    input = f"projects/{project_id}/locations/{location}/inputs/{input_id}"
    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"

    channel = live_stream_v1.types.Channel(
        name=name,
        input_attachments=[
            live_stream_v1.types.InputAttachment(
                key="updated-input",
                input=input,
            ),
        ],
    )
    update_mask = field_mask.FieldMask(paths=["input_attachments"])

    operation = client.update_channel(channel=channel, update_mask=update_mask)
    response = operation.result(60)
    print(f"Updated channel: {response.name}")

    return response

Start or stop a channel

Use the following methods to start or stop a channel. The server creates a part of the video pipeline when the channels.start request is received. The server releases a part of the video pipeline when the channels.stop request is received.

Start a channel

To start a channel, use the projects.locations.channels.start method.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location where your channel is located; use one of the supported regions:
    • 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: a user-defined identifier for the channel

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// 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: %v", 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: %v", err)
	}
	_, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Started channel")
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


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.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      ChannelName name = ChannelName.of(projectId, location, channelId);
      livestreamServiceClient.startChannelAsync(name).get(1, TimeUnit.MINUTES);
      System.out.println("Started channel");
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * 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();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)


def start_channel(project_id: str, location: str, channel_id: str) -> None:
    """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)
    operation.result(60)
    print("Started channel")

Stop a channel

To stop a channel, use the projects.locations.channels.stop method.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location where your channel is located; use one of the supported regions:
    • 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: a user-defined identifier for the channel

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// 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: %v", 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: %v", err)
	}
	_, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Stopped channel")
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


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.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      ChannelName name = ChannelName.of(projectId, location, channelId);
      livestreamServiceClient.stopChannelAsync(name).get(1, TimeUnit.MINUTES);
      System.out.println("Stopped channel");
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * 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();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)


def stop_channel(project_id: str, location: str, channel_id: str) -> None:
    """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)
    operation.result(60)
    print("Stopped channel")

List channels

To list all of the channels you created in a location, use the projects.locations.channels.list method.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location where your channel is located; use one of the supported regions:
    • 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

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "channels": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/my-channel",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "activeInput": "INPUT_ID",
      "output": {
        "uri": "gs://BUCKET_NAME"
      },
      ...
    },
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/my-channel2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "activeInput": "my-other-input",
      "output": {
        "uri": "gs://BUCKET_NAME"
      },
      ...
    }
  ]
}

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/api/iterator"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// listChannels lists all channels for a given location.
func listChannels(w io.Writer, projectID, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	req := &livestreampb.ListChannelsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListChannels(ctx, req)
	fmt.Fprintln(w, "Channels:")

	for {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListChannels: %v", err)
		}
		fmt.Fprintln(w, response.GetName())
	}
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


import com.google.cloud.video.livestream.v1.Channel;
import com.google.cloud.video.livestream.v1.ListChannelsRequest;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.LocationName;
import java.io.IOException;

public class ListChannels {

  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";

    listChannels(projectId, location);
  }

  public static void listChannels(String projectId, String location) 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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var listChannelsRequest =
          ListChannelsRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .build();

      LivestreamServiceClient.ListChannelsPagedResponse response =
          livestreamServiceClient.listChannels(listChannelsRequest);
      System.out.println("Channels:");

      for (Channel channel : response.iterateAll()) {
        System.out.println(channel.getName());
      }
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function listChannels() {
  const [channels] = await livestreamServiceClient.listChannels({
    parent: livestreamServiceClient.locationPath(projectId, location),
  });
  console.info('Channels:');
  for (const channel of channels) {
    console.info(channel.name);
  }
}

listChannels();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)


def list_channels(project_id: str, location: str) -> list:
    """Lists all channels in a location.
    Args:
        project_id: The GCP project ID.
        location: The location of the channels."""

    client = LivestreamServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    page_result = client.list_channels(parent=parent)
    print("Channels:")

    responses = []
    for response in page_result:
        print(response.name)
        responses.append(response)

    return responses

Delete a channel

To delete a channel, use the projects.locations.channels.delete method. You must stop the channel and delete all channel events before you can delete the channel.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number; this is listed below the Project ID on the IAM Settings page
  • LOCATION: the location where your channel is located; use one of the supported regions:
    • 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: a user-defined identifier for the channel

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

Go

Before trying this sample, follow the Go setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "google.golang.org/genproto/googleapis/cloud/video/livestream/v1"
)

// 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: %v", 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: %v", err)
	}
	err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Deleted channel")
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Java API reference documentation.


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.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var deleteChannelRequest =
          DeleteChannelRequest.newBuilder()
              .setName(ChannelName.of(projectId, location, channelId).toString())
              .build();

      livestreamServiceClient.deleteChannelAsync(deleteChannelRequest).get(1, TimeUnit.MINUTES);
      System.out.println("Deleted channel");
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Node.js API reference documentation.

/**
 * 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();

Python

Before trying this sample, follow the Python setup instructions in the Live Stream API quickstart using client libraries. For more information, see the Live Stream API Python API reference documentation.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)


def delete_channel(project_id: str, location: str, channel_id: str) -> None:
    """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)
    operation.result(60)
    print("Deleted channel")

What's next

Learn how to create and manage channel events.