채널 만들기 및 관리

이 페이지에서는 Live Stream API 채널을 만들고 관리하는 방법을 보여줍니다. 채널 리소스는 사용자 정의 "스트리밍" 작업을 수행하는 프로세서를 나타냅니다. 스트리밍 작업에는 입력 엔드포인트를 통해 입력 스트림을 가져오고 입력 스트림을 여러 버전으로 트랜스코딩하고 지정된 위치의 특정 형식으로 출력 실시간 스트림을 게시하는 작업이 포함됩니다.

Google Cloud 프로젝트 및 인증 설정

Google Cloud 프로젝트와 사용자 인증 정보를 만들지 않은 경우 시작하기 전에를 참조하세요.

기본 요건

채널 만들기

채널 이벤트를 만들려면 projects.locations.channels.create 메서드를 사용합니다. 다음 샘플은 HLS 실시간 스트림을 생성하는 채널을 만듭니다. 실시간 스트림은 단일 고화질(1280x720) 버전으로 구성됩니다.

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: 만들려는 채널의 사용자 정의 식별자입니다. 이 값은 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
}
이 명령어는 요청 진행 상태를 추적하는 데 사용할 수 있는 장기 실행 작업(LRO)을 만듭니다. 자세한 내용은 장기 실행 작업 관리를 참조하세요.

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 CreateChannelSample
{
    public async Task<Channel> CreateChannelAsync(
         string projectId, string locationId, string channelId, string inputId, string outputUri)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        InputAttachment inputAttachment = new InputAttachment
        {
            Key = "my-input",
            InputAsInputName = InputName.FromProjectLocationInput(projectId, locationId, inputId)
        };

        VideoStream videoStream = new VideoStream
        {
            H264 = new VideoStream.Types.H264CodecSettings
            {
                Profile = "high",
                BitrateBps = 3000000,
                FrameRate = 30,
                HeightPixels = 720,
                WidthPixels = 1280
            }
        };

        ElementaryStream elementaryStreamVideo = new ElementaryStream
        {
            Key = "es_video",
            VideoStream = videoStream
        };

        AudioStream audioStream = new AudioStream
        {
            Codec = "aac",
            ChannelCount = 2,
            BitrateBps = 160000
        };

        ElementaryStream elementaryStreamAudio = new ElementaryStream
        {
            Key = "es_audio",
            AudioStream = audioStream
        };

        MuxStream muxVideo = new MuxStream
        {
            Key = "mux_video",
            ElementaryStreams = { "es_video" },
            SegmentSettings = new SegmentSettings
            {
                SegmentDuration = new Google.Protobuf.WellKnownTypes.Duration
                {
                    Seconds = 2
                }
            }
        };

        MuxStream muxAudio = new MuxStream
        {
            Key = "mux_audio",
            ElementaryStreams = { "es_audio" },
            SegmentSettings = new SegmentSettings
            {
                SegmentDuration = new Google.Protobuf.WellKnownTypes.Duration
                {
                    Seconds = 2
                }
            }
        };

        CreateChannelRequest request = new CreateChannelRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
            ChannelId = channelId,
            Channel = new Channel
            {
                InputAttachments = { inputAttachment },
                Output = new Channel.Types.Output
                {
                    Uri = outputUri
                },
                ElementaryStreams = { elementaryStreamVideo, elementaryStreamAudio },
                MuxStreams = { muxVideo, muxAudio },
                Manifests = {
                    new Manifest {
                        FileName = "manifest.m3u8",
                        Type = Manifest.Types.ManifestType.Hls,
                        MuxStreams = { "mux_video", "mux_audio" },
                        MaxSegmentCount = 5
                    }
                }
            }
        };

        // Make the request.
        Operation<Channel, OperationMetadata> response = await client.CreateChannelAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<Channel, 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"

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

	livestream "cloud.google.com/go/video/livestream/apiv1"
	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
)

// 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: %w", 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: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %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.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.
    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();
    // First API call in a project can take up to 10 minutes.
    Channel result =
        livestreamServiceClient
            .createChannelAsync(createChannelRequest)
            .get(10, TimeUnit.MINUTES);
    System.out.println("Channel: " + 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';
// 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();

PHP

Live Stream API용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Live Stream API 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Live Stream API PHP API 참고 문서를 확인하세요.

Live Stream API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Video\LiveStream\V1\AudioStream;
use Google\Cloud\Video\LiveStream\V1\Channel;
use Google\Cloud\Video\LiveStream\V1\ElementaryStream;
use Google\Cloud\Video\LiveStream\V1\InputAttachment;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\CreateChannelRequest;
use Google\Cloud\Video\LiveStream\V1\Manifest;
use Google\Cloud\Video\LiveStream\V1\MuxStream;
use Google\Cloud\Video\LiveStream\V1\SegmentSettings;
use Google\Cloud\Video\LiveStream\V1\VideoStream;
use Google\Protobuf\Duration;

/**
 * Creates 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 created
 * @param string  $inputId            The ID of the input for the channel
 * @param string  $outputUri          Uri of the channel output folder in a
 *                                    Cloud Storage bucket. (e.g.
 *                                    "gs://my-bucket/my-output-folder/")
 */
function create_channel(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $inputId,
    string $outputUri
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $parent = $livestreamClient->locationName($callingProjectId, $location);
    $channelName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    $inputName = $livestreamClient->inputName($callingProjectId, $location, $inputId);

    $channel = (new Channel())
        ->setName($channelName)
        ->setInputAttachments([
            new InputAttachment([
                'key' => 'my-input',
                'input' => $inputName
            ])
        ])
        ->setElementaryStreams([
            new ElementaryStream([
                'key' => 'es_video',
                'video_stream' => new VideoStream([
                    'h264' => new VideoStream\H264CodecSettings([
                        'profile' => 'high',
                        'width_pixels' => 1280,
                        'height_pixels' => 720,
                        'bitrate_bps' => 3000000,
                        'frame_rate' => 30
                    ])
                ]),
            ]),
            new ElementaryStream([
                'key' => 'es_audio',
                'audio_stream' => new AudioStream([
                    'codec' => 'aac',
                    'channel_count' => 2,
                    'bitrate_bps' => 160000
                ])
            ])
        ])
        ->setOutput(new Channel\Output(['uri' => $outputUri]))
        ->setMuxStreams([
            new MuxStream([
                'key' => 'mux_video',
                'elementary_streams' => ['es_video'],
                'segment_settings' => new SegmentSettings([
                    'segment_duration' => new Duration(['seconds' => 2])
                ])
            ]),
            new MuxStream([
                'key' => 'mux_audio',
                'elementary_streams' => ['es_audio'],
                'segment_settings' => new SegmentSettings([
                    'segment_duration' => new Duration(['seconds' => 2])
                ])
            ]),
        ])
        ->setManifests([
            new Manifest([
                'file_name' => 'manifest.m3u8',
                'type' => Manifest\ManifestType::HLS,
                'mux_streams' => ['mux_video', 'mux_audio'],
                'max_segment_count' => 5
            ])
        ]);

    // Run the channel creation request. The response is a long-running operation ID.
    $request = (new CreateChannelRequest())
        ->setParent($parent)
        ->setChannel($channel)
        ->setChannelId($channelId);
    $operationResponse = $livestreamClient->createChannel($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Channel: %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,
)
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
) -> live_stream_v1.types.Channel:
    """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(600)
    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"

##
# Create 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")
# @param input_id [String] Your input name (e.g. "my-input")
# @param output_uri [String] Uri of the channel output folder in a Cloud Storage
#     bucket. (e.g. "gs://my-bucket/my-output-folder/";)
#
def create_channel project_id:, location:, channel_id:, input_id:, output_uri:
  # 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
  # Build the resource name of the input.
  input_path = client.input_path project: project_id, location: location, input: input_id

  # Set the channel fields.
  new_channel = {
    input_attachments: [
      {
        key: "my-input",
        input: input_path
      }
    ],
    output: {
      uri: output_uri
    },
    elementary_streams: [
      {
        key: "es_video",
        video_stream: {
          h264: {
            profile: "high",
            bitrate_bps: 3_000_000,
            frame_rate: 30,
            height_pixels: 720,
            width_pixels: 1280
          }
        }
      },
      {
        key: "es_audio",
        audio_stream: {
          codec: "aac",
          channel_count: 2,
          bitrate_bps: 160_000
        }
      }
    ],
    mux_streams: [
      {
        key: "mux_video",
        elementary_streams: [
          "es_video"
        ],
        segment_settings: {
          segment_duration: {
            seconds: 2
          }
        }
      },
      {
        key: "mux_audio",
        elementary_streams: [
          "es_audio"
        ],
        segment_settings: {
          segment_duration: {
            seconds: 2
          }
        }
      }
    ],
    manifests: [
      {
        file_name: "main.m3u8",
        type: Google::Cloud::Video::LiveStream::V1::Manifest::ManifestType::HLS,
        mux_streams: [
          "mux_video", "mux_audio"
        ],
        max_segment_count: 5
      }
    ]
  }

  operation = client.create_channel parent: parent, channel: new_channel, channel_id: channel_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 channel name.
  puts "Channel: #{operation.response.name}"
end

채널 세부정보 가져오기

채널 세부정보를 가져오려면 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_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"
}

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

채널 업데이트

채널을 업데이트하려면 projects.locations.channels.patch 메서드를 사용합니다.

다음 예시에서는 채널에서 사용하는 입력 엔드포인트를 업데이트합니다. 모든 필드를 업데이트할 수 있는 것은 아닙니다. 지원되는 필드 목록을 참조하세요.

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: 업데이트할 채널의 사용자 정의 식별자입니다.
  • 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/channels/CHANNEL_ID",
    "verb": "update",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}
이 명령어는 요청 진행 상태를 추적하는 데 사용할 수 있는 장기 실행 작업(LRO)을 만듭니다. 자세한 내용은 장기 실행 작업 관리를 참조하세요.

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 UpdateChannelSample
{
    public async Task<Channel> UpdateChannelAsync(
         string projectId, string locationId, string channelId, string inputId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        InputAttachment inputAttachment = new InputAttachment
        {
            Key = "updated-input",
            InputAsInputName = InputName.FromProjectLocationInput(projectId, locationId, inputId)
        };

        UpdateChannelRequest request = new UpdateChannelRequest
        {
            Channel = new Channel
            {
                ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId),
                InputAttachments = { inputAttachment }
            },
            UpdateMask = new FieldMask { Paths = { "input_attachments" } }
        };

        // Make the request.
        Operation<Channel, OperationMetadata> response = await client.UpdateChannelAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<Channel, 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"
	"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: %w", 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: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Updated 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.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.
    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();
    // First API call in a project can take up to 10 minutes.
    Channel result =
        livestreamServiceClient
            .updateChannelAsync(updateChannelRequest)
            .get(10, TimeUnit.MINUTES);
    System.out.println("Updated channel: " + 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';
// 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();

PHP

Live Stream API용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Live Stream API 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Live Stream API PHP API 참고 문서를 확인하세요.

Live Stream API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Video\LiveStream\V1\Channel;
use Google\Cloud\Video\LiveStream\V1\InputAttachment;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\UpdateChannelRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates an existing channel with a different input.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel and the input
 * @param string  $channelId          The ID of the channel to be updated
 * @param string  $inputId            The ID of the existing input
 */
function update_channel(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $inputId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $channelName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    $inputName = $livestreamClient->inputName($callingProjectId, $location, $inputId);

    $inputAttachment = (new InputAttachment())
        ->setKey('updated-input')
        ->setInput($inputName);
    $channel = (new Channel())
        ->setName($channelName)
        ->setInputAttachments([$inputAttachment]);

    $updateMask = new FieldMask([
        'paths' => ['input_attachments']
    ]);

    // Run the channel update request. The response is a long-running operation ID.
    $request = (new UpdateChannelRequest())
        ->setChannel($channel)
        ->setUpdateMask($updateMask);
    $operationResponse = $livestreamClient->updateChannel($request);

    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated channel: %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,
)
from google.protobuf import field_mask_pb2 as field_mask

def update_channel(
    project_id: str, location: str, channel_id: str, input_id: str
) -> live_stream_v1.types.Channel:
    """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(600)
    print(f"Updated 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"

##
# Update 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")
# @param input_id [String] The input name to update the channel with (e.g. "my-updated-input")
#
def update_channel project_id:, location:, channel_id:, input_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

  # Build the resource name of the input.
  input = client.input_path project: project_id, location: location, input: input_id

  # Set the update mask.
  update_mask = { paths: ["input_attachments"] }

  # Update the channel input_attachments config field.
  update_channel = {
    name: name,
    input_attachments: [
      {
        key: "updated-input",
        input: input
      }
    ]
  }

  operation = client.update_channel update_mask: update_mask, channel: update_channel

  # 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 channel name.
  puts "Updated channel: #{operation.response.name}"
  puts "Updated input_attachments config: #{operation.response.input_attachments[0].key}"
end

채널 시작 또는 중지

다음 메서드를 사용하여 채널을 시작하거나 중지합니다. channels.start 요청이 수신되면 서버는 동영상 파이프라인의 일부를 만듭니다. channels.stop 요청이 수신되면 서버는 동영상 파이프라인의 일부를 출시합니다.

채널 시작

채널을 시작하려면 projects.locations.channels.start 메서드를 사용합니다.

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
}
이 명령어는 요청 진행 상태를 추적하는 데 사용할 수 있는 장기 실행 작업(LRO)을 만듭니다. 자세한 내용은 장기 실행 작업 관리를 참조하세요.

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

채널 중지

채널을 중지하려면 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
}
이 명령어는 요청 진행 상태를 추적하는 데 사용할 수 있는 장기 실행 작업(LRO)을 만듭니다. 자세한 내용은 장기 실행 작업 관리를 참조하세요.

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

채널 나열

한 위치에서 만든 모든 채널을 나열하려면 projects.locations.channels.list 메서드를 사용합니다.

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

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "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"
      },
      ...
    }
  ]
}

C#

Live Stream API용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Live Stream API 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Live Stream API C# API 참고 문서를 확인하세요.

Live Stream API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.LiveStream.V1;
using System.Collections.Generic;
using System.Linq;

public class ListChannelsSample
{
    public IList<Channel> ListChannels(
        string projectId, string regionId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        ListChannelsRequest request = new ListChannelsRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, regionId)
        };

        // Make the request.
        PagedEnumerable<ListChannelsResponse, Channel> response = client.ListChannels(request);

        // The returned sequence will lazily perform RPCs as it's being iterated over.
        return response.ToList();
    }
}

Go

Live Stream API용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Live Stream API 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Live Stream API Go API 참고 문서를 확인하세요.

Live Stream API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/api/iterator"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
)

// 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: %w", 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: %w", err)
		}
		fmt.Fprintln(w, response.GetName())
	}
	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.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. 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 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

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

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

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

async function listChannels() {
  const iterable = await livestreamServiceClient.listChannelsAsync({
    parent: livestreamServiceClient.locationPath(projectId, location),
  });
  console.info('Channels:');
  for await (const response of iterable) {
    console.log(response.name);
  }
}

listChannels();

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\ListChannelsRequest;

/**
 * Lists the channels for a given location.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channels
 */
function list_channels(
    string $callingProjectId,
    string $location
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $parent = $livestreamClient->locationName($callingProjectId, $location);
    $request = (new ListChannelsRequest())
        ->setParent($parent);

    $response = $livestreamClient->listChannels($request);
    // Print the channel list.
    $channels = $response->iterateAllElements();
    print('Channels:' . PHP_EOL);
    foreach ($channels as $channel) {
        printf('%s' . PHP_EOL, $channel->getName());
    }
}

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,
    pagers,
)

def list_channels(project_id: str, location: str) -> pagers.ListChannelsPager:
    """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

Ruby

Live Stream API용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Live Stream API 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Live Stream API Ruby API 참고 문서를 확인하세요.

Live Stream API에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

require "google/cloud/video/live_stream"

##
# List the channels
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
#
def list_channels project_id:, location:
  # 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

  # Get the list of channels.
  response = client.list_channels parent: parent

  puts "Channels:"
  # Print out all channels.
  response.each do |channel|
    puts channel.name
  end
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
}
이 명령어는 요청 진행 상태를 추적하는 데 사용할 수 있는 장기 실행 작업(LRO)을 만듭니다. 자세한 내용은 장기 실행 작업 관리를 참조하세요.

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

다음 단계

채널 이벤트 만들기 및 관리 방법 알아보기