Créer un canal avec une entrée de sauvegarde

Créez un canal avec deux flux d'entrée, l'un étant le flux de secours de l'autre flux d'entrée. Si le flux d'entrée principal est déconnecté en raison de problèmes de réseau, le canal bascule automatiquement pour utiliser le flux d'entrée secondaire comme source d'entrée. Une fois que le flux d'entrée principal est de nouveau en ligne, le canal revient automatiquement au flux d'entrée principal en tant que source d'entrée.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream C#.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.LiveStream.V1;
using Google.LongRunning;
using System.Threading.Tasks;

public class CreateChannelWithBackupInputSample
{
    public async Task<Channel> CreateChannelWithBackupInputAsync(
         string projectId, string locationId, string channelId, string primaryInputId, string backupInputId, string outputUri)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        InputAttachment primaryInputAttachment = new InputAttachment
        {
            Key = "my-primary-input",
            InputAsInputName = InputName.FromProjectLocationInput(projectId, locationId, primaryInputId),
            AutomaticFailover = new InputAttachment.Types.AutomaticFailover
            {
                InputKeys = { "my-backup-input" }
            }
        };

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

        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 = { primaryInputAttachment, backupInputAttachment },
                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

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream Go.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

// createChannelWithBackupInput creates a channel with a failover backup input.
func createChannelWithBackupInput(w io.Writer, projectID, location, channelID, primaryInputID, backupInputID, outputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// primaryInputID := "my-primary-input"
	// backupInputID := "my-backup-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()

	primaryInput := fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, primaryInputID)
	backupInput := fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, backupInputID)
	automaticFailover := &livestreampb.InputAttachment_AutomaticFailover{
		InputKeys: []string{"my-backup-input"},
	}

	req := &livestreampb.CreateChannelRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ChannelId: channelID,
		Channel: &livestreampb.Channel{
			InputAttachments: []*livestreampb.InputAttachment{
				{
					Key:               "my-primary-input",
					Input:             primaryInput,
					AutomaticFailover: automaticFailover,
				},
				{
					Key:   "my-backup-input",
					Input: backupInput,
				},
			},
			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

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream Java.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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.InputAttachment.AutomaticFailover;
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 CreateChannelWithBackupInput {

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

    createChannelWithBackupInput(
        projectId, location, channelId, primaryInputId, backupInputId, outputUri);
  }

  public static void createChannelWithBackupInput(
      String projectId,
      String location,
      String channelId,
      String primaryInputId,
      String backupInputId,
      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-primary-input")
                            .setInput(
                                InputName.of(projectId, location, primaryInputId).toString())
                            .setAutomaticFailover(
                                AutomaticFailover.newBuilder()
                                    .addInputKeys("my-backup-input")
                                    .build())
                            .build())
                    .addInputAttachments(
                        1,
                        InputAttachment.newBuilder()
                            .setKey("my-backup-input")
                            .setInput(
                                InputName.of(projectId, location, backupInputId).toString()))
                    .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

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream Node.js.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// channelId = 'my-channel';
// primaryInputId = 'my-primary-input';
// backupInputId = 'my-backup-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 createChannelWithBackupInput() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.locationPath(projectId, location),
    channelId: channelId,
    channel: {
      inputAttachments: [
        {
          key: 'my-primary-input',
          input: livestreamServiceClient.inputPath(
            projectId,
            location,
            primaryInputId
          ),
          automaticFailover: {
            inputKeys: ['my-backup-input'],
          },
        },
        {
          key: 'my-backup-input',
          input: livestreamServiceClient.inputPath(
            projectId,
            location,
            backupInputId
          ),
        },
      ],
      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}`);
}

createChannelWithBackupInput();

PHP

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream PHP.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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 with a backup input.
 *
 * @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  $primaryInputId     The ID of the primary input for the channel
 * @param string  $backupInputId      The ID of the backup 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_with_backup_input(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $primaryInputId,
    string $backupInputId,
    string $outputUri
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $parent = $livestreamClient->locationName($callingProjectId, $location);
    $channelName = $livestreamClient->channelName($callingProjectId, $location, $channelId);
    $primaryInputName = $livestreamClient->inputName($callingProjectId, $location, $primaryInputId);
    $backupInputName = $livestreamClient->inputName($callingProjectId, $location, $backupInputId);

    $channel = (new Channel())
        ->setName($channelName)
        ->setInputAttachments([
            new InputAttachment([
                'key' => 'my-primary-input',
                'input' => $primaryInputName,
                'automatic_failover' => new InputAttachment\AutomaticFailover([
                    'input_keys' => ['my-backup-input']
                ])
            ]),
            new InputAttachment([
                'key' => 'my-backup-input',
                'input' => $backupInputName
            ])
        ])
        ->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

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream Python.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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_with_backup_input(
    project_id: str,
    location: str,
    channel_id: str,
    primary_input_id: str,
    backup_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.
        primary_input_id: The user-defined primary input ID.
        backup_input_id: The user-defined backup input ID.
        output_uri: Uri of the channel output folder in a Cloud Storage bucket."""

    client = LivestreamServiceClient()
    parent = f"projects/{project_id}/locations/{location}"
    primary_input = (
        f"projects/{project_id}/locations/{location}/inputs/{primary_input_id}"
    )
    backup_input = (
        f"projects/{project_id}/locations/{location}/inputs/{backup_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-primary-input",
                input=primary_input,
                automatic_failover=live_stream_v1.types.InputAttachment.AutomaticFailover(
                    input_keys=["my-backup-input"],
                ),
            ),
            live_stream_v1.types.InputAttachment(
                key="my-backup-input",
                input=backup_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

Pour savoir comment installer et utiliser la bibliothèque cliente pour l'API Live Stream, consultez Bibliothèques clientes de l'API Live Stream. Pour en savoir plus, consultez la documentation de référence de l'API Live Stream Ruby.

Pour vous authentifier auprès de l'API Live Stream, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

require "google/cloud/video/live_stream"

##
# Create a channel with a failover backup input
#
# @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 primary_input_id [String] Your primary input name (e.g. "my-primary-input")
# @param backup_input_id [String] Your backup input name (e.g. "my-backup-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_with_backup_input project_id:, location:, channel_id:, primary_input_id:, backup_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 inputs.
  primary_input_path = client.input_path project: project_id, location: location, input: primary_input_id
  backup_input_path = client.input_path project: project_id, location: location, input: backup_input_id

  # Set the channel fields.
  new_channel = {
    input_attachments: [
      {
        key: "my-primary-input",
        input: primary_input_path,
        automatic_failover: {
          input_keys: ["my-backup-input"]
        }
      },
      {
        key: "my-backup-input",
        input: backup_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

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.