Kurzanleitung für einen HLS-Livestream

Auf dieser Seite wird beschrieben, wie Sie einen einfachen HLS-Livestreamjob erstellen. mithilfe der Standardeinstellungen der Live Stream API und curl, PowerShell oder der Clientbibliotheken.

Sie können diese Kurzanleitung auch direkt in der Google Cloud Console ausführen mit einer der folgenden Programmiersprachen:

Hinweise

  1. Melden Sie sich bei Ihrem Google Cloud-Konto an. Wenn Sie mit Google Cloud noch nicht vertraut sind, erstellen Sie ein Konto, um die Leistungsfähigkeit unserer Produkte in der Praxis sehen und bewerten zu können. Neukunden erhalten außerdem ein Guthaben von 300 $, um Arbeitslasten auszuführen, zu testen und bereitzustellen.
  2. Installieren Sie die Google Cloud CLI.
  3. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

    gcloud init
  4. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  5. Die Abrechnung für das Google Cloud-Projekt muss aktiviert sein.

  6. Aktivieren Sie die Live Stream API:

    gcloud services enable livestream.googleapis.com
  7. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

    gcloud auth application-default login
  8. Gewähren Sie Ihrem Google-Konto Rollen. Führen Sie den folgenden Befehl für jede der folgenden IAM-Rollen einmal aus: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • Ersetzen Sie PROJECT_ID durch Ihre Projekt-ID.
    • Ersetzen Sie EMAIL_ADDRESS durch Ihre E-Mail-Adresse.
    • Ersetzen Sie ROLE durch jede einzelne Rolle.
  9. Installieren Sie die Google Cloud CLI.
  10. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

    gcloud init
  11. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Die Abrechnung für das Google Cloud-Projekt muss aktiviert sein.

  13. Aktivieren Sie die Live Stream API:

    gcloud services enable livestream.googleapis.com
  14. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

    gcloud auth application-default login
  15. Gewähren Sie Ihrem Google-Konto Rollen. Führen Sie den folgenden Befehl für jede der folgenden IAM-Rollen einmal aus: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • Ersetzen Sie PROJECT_ID durch Ihre Projekt-ID.
    • Ersetzen Sie EMAIL_ADDRESS durch Ihre E-Mail-Adresse.
    • Ersetzen Sie ROLE durch jede einzelne Rolle.

Cloud Storage-Bucket erstellen

Cloud Storage-Bucket zum Speichern des Livestreammanifests und des Livestream-Segments erstellen Dateien.

Google Cloud Console

  1. Wechseln Sie in der Google Cloud Console zur Cloud Storage-Seite Buckets.

    Zur Seite „Buckets“

  2. Klicken Sie auf Bucket erstellen.
  3. Geben Sie auf der Seite Bucket erstellen die Bucket-Informationen ein. Klicken Sie auf Weiter, um mit dem nächsten Schritt fortzufahren.
    • Geben Sie unter Bucket benennen einen Namen ein, der den Anforderungen für Bucket-Namen entspricht.
    • Gehen Sie unter Speicherort für Daten auswählen folgendermaßen vor:
      • Wählen Sie eine Option für Standorttyp aus.
      • Wählen Sie eine Standort-Option aus.
    • Wählen Sie unter Standardspeicherklasse für Ihre Daten auswählen Folgendes aus: Standard.
    • Wählen Sie unter Zugriffssteuerung für Objekte auswählen eine Option für die Zugriffssteuerung aus.
    • Geben Sie für Erweiterte Einstellungen (optional) eine Verschlüsselungsmethode, eine Aufbewahrungsrichtlinie oder Bucket-Labels an.
  4. Klicken Sie auf Erstellen.

Befehlszeile

    Cloud Storage-Bucket erstellen:
    gcloud storage buckets create gs://BUCKET_NAME
    Ersetzen Sie BUCKET_NAME durch einen Bucket-Namen, der den Anforderungen für Bucket-Namen entspricht:

Encoder installieren

Für die API benötigst du einen Encoder, um Eingabestreams zu generieren die die API verarbeitet.

ffmpeg als diese Seite installieren behandelt die Verwendung von ffmpeg zum Generieren von Eingabestreams. Sie können dies installieren in Cloud Shell mit dem folgenden Befehl ausführen.

sudo apt install ffmpeg

Eingabeendpunkt erstellen

Um einen Livestream zu starten, musst du zuerst das projects.locations.inputs.create Methode zum Erstellen eines Eingabeendpunkts. Sie senden den Eingabestream an diesen Endpunkt.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem die Eingabe erstellt werden soll endpoint; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID: eine benutzerdefinierte Kennung für die neue Eingabe Endpunkt, der erstellt werden soll (an den Sie den Eingabestream senden). Dieser Wert muss 1–63 Zeichen lang sein und mit [a-z0-9] beginnen und enden. kann Bindestriche (-) zwischen den Zeichen enthalten. Beispiel: my-input

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

public class CreateInputSample
{
    public async Task<Input> CreateInputAsync(
         string projectId, string locationId, string inputId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        CreateInputRequest request = new CreateInputRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
            InputId = inputId,
            Input = new Input
            {
                Type = Input.Types.Type.RtmpPush
            }
        };

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

        // Poll until the returned long-running operation is complete.
        Operation<Input, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

// createInput creates an input endpoint. You send an input video stream to this
// endpoint.
func createInput(w io.Writer, projectID, location, inputID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputID := "my-input"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.CreateInputRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		InputId: inputID,
		Input: &livestreampb.Input{
			Type: livestreampb.Input_RTMP_PUSH,
		},
	}
	// Creates the input.
	op, err := client.CreateInput(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateInput: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

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

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.video.livestream.v1.CreateInputRequest;
import com.google.cloud.video.livestream.v1.Input;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInput {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String inputId = "my-input-id";

    createInput(projectId, location, inputId);
  }

  public static void createInput(String projectId, String location, String inputId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    var createInputRequest =
        CreateInputRequest.newBuilder()
            .setParent(LocationName.of(projectId, location).toString())
            .setInputId(inputId)
            .setInput(Input.newBuilder().setType(Input.Type.RTMP_PUSH).build())
            .build();
    // First API call in a project can take up to 15 minutes.
    Input result =
        livestreamServiceClient.createInputAsync(createInputRequest).get(15, TimeUnit.MINUTES);
    System.out.println("Input: " + result.getName());
    livestreamServiceClient.close();
  }
}

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

async function createInput() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.locationPath(projectId, location),
    inputId: inputId,
    input: {
      type: 'RTMP_PUSH',
    },
  };

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

createInput();

PHP

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Video\LiveStream\V1\Input;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\CreateInputRequest;

/**
 * Creates an input. You send an input video stream to this endpoint.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the input
 * @param string  $inputId            The ID of the input to be created
 */
function create_input(
    string $callingProjectId,
    string $location,
    string $inputId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $parent = $livestreamClient->locationName($callingProjectId, $location);
    $input = (new Input())
        ->setType(Input\Type::RTMP_PUSH);

    // Run the input creation request. The response is a long-running operation ID.
    $request = (new CreateInputRequest())
        ->setParent($parent)
        ->setInput($input)
        ->setInputId($inputId);
    $operationResponse = $livestreamClient->createInput($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Input: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import argparse

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


def create_input(
    project_id: str, location: str, input_id: str
) -> live_stream_v1.types.Input:
    """Creates an input.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the input.
        input_id: The user-defined input ID."""

    client = LivestreamServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    input = live_stream_v1.types.Input(
        type_="RTMP_PUSH",
    )
    operation = client.create_input(parent=parent, input=input, input_id=input_id)
    response = operation.result(900)
    print(f"Input: {response.name}")

    return response

Ruby

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "google/cloud/video/live_stream"

##
# Create an input endpoint
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param input_id [String] Your input name (e.g. "my-input")
#
def create_input project_id:, location:, input_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  # Set the input fields.
  new_input = {
    type: Google::Cloud::Video::LiveStream::V1::Input::Type::RTMP_PUSH
  }

  operation = client.create_input parent: parent, input: new_input, input_id: input_id

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the input name.
  puts "Input: #{operation.response.name}"
end

Zurückgegebene OPERATION_ID kopieren nach im nächsten Abschnitt.

Ergebnis prüfen

Verwenden Sie den projects.locations.operations.get. , um zu prüfen, ob der Eingabeendpunkt erstellt wurde. Wenn die Antwort Folgendes enthält: "done: false", wiederholen Sie den Befehl, bis die Antwort "done: true" enthält. Das Erstellen des ersten Eingabeendpunkts in einer Region kann bis zu 10 Minuten dauern.

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich der Eingabeendpunkt befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • OPERATION_ID: die Kennung für den Vorgang

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "endTime": END_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.Input",
    "name": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
    "createTime": CREATE_TIME,
    "updateTime": UPDATE_TIME,
    "type": "RTMP_PUSH",
    "uri":  INPUT_STREAM_URI, # For example, "rtmp://1.2.3.4/live/b8ebdd94-c8d9-4d88-a16e-b963c43a953b",
    "tier": "HD"
  }
}

Suchen Sie das Feld uri und kopieren Sie die zurückgegebene INPUT_STREAM_URI, um sie später im Feld Send the Input stream (Eingabestream).

Kanäle erstellen

Um den Eingabestream in einen Ausgabestream zu transcodieren, müssen Sie einen Kanalressource.

Verwenden Sie zum Erstellen eines Channels das projects.locations.channels.create . Im folgenden Beispiel wird ein Kanal erstellt, der eine HLS generiert. einen Livestream, der aus einer einzelnen HD-Wiedergabe (1280 x 720) besteht.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Speicherort, an dem die Channel: eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal, der verwendet werden soll. erstellen; Dieser Wert muss 1–63 Zeichen lang sein, mit [a-z0-9] beginnen und enden. darf Bindestriche (-) zwischen den Zeichen enthalten
  • INPUT_ID: die benutzerdefinierte Kennung für den Eingabeendpunkt
  • BUCKET_NAME: der Name von Cloud Storage Bucket, den Sie zum Speichern des Manifests und der Segmentdateien des Livestreams erstellt haben

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

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

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Hol dir den Kanal

Du kannst das Ergebnis der Kanalerstellung prüfen. Vorgang unter Verwendung der neuen Vorgangs-ID.

Sobald der Channel erstellt ist, verwenden Sie projects.locations.channels.get um den Kanalstatus abzufragen.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "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": [
    {
      "key": "manifest_hls",
      "fileName": "main.m3u8",
      "type": "HLS",
      "muxStreams": [
        "mux_video_ts",
      ],
      "maxSegmentCount": 5,
      "segmentKeepDuration": "60s"
    }
  ],
  "streamingState": "STOPPED"
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Die vollständige Antwort enthält das folgende Feld. (Teile des Codes Die Beispiele oben geben nur bestimmte Felder in der Antwort zurück, können aber geändert werden zu vollständige Antwort zurückgeben.)

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

Diese Antwort bedeutet, dass du den Kanal jetzt starten kannst.

Den Kanal starten

Verwenden Sie die Methode projects.locations.channels.start um den Kanal zu starten. Ein Kanal muss erst gestartet werden, bevor er Annahmen akzeptieren kann. Eingabestreams oder generieren einen Ausgabestream.

Das Starten des ersten Kanals in einer Region dauert etwa 10 Minuten.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
    "verb": "start",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Eingabestream senden

Hier kannst du herausfinden, ob der Kanal gestartet wurde. Informationen wie zuvor. Die Antwort sollte Folgendes enthalten:

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

Da der Kanal nun bereit ist, senden Sie einen Testeingabestream an den Eingabeendpunkt, um den Livestream zu generieren.

Öffnen Sie ein neues Terminalfenster. Führen Sie den folgenden Befehl mit der Methode INPUT_STREAM_URI vom Prüfen Sie den Ergebnisbereich:

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

Prüfen, ob der Kanal streamt

So prüfst du den Status des Livestreamings: die Kanalinformationen abrufen. Die Antwort sollte Folgendes enthalten:

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

Inhalt im Cloud Storage-Bucket prüfen

Öffnen Sie den Cloud Storage-Bucket. Prüfen Sie, ob die folgenden Dateien enthalten sind: und Verzeichnisse:

  • main.m3u8
  • mux_video_ts/
    • Mehrere segment-segment-number.ts-Dateien
    • Eine einzelne index-1.m3u8 Datei

Generierten Livestream wiedergeben

Führen Sie die folgenden Schritte aus, um die generierte Mediadatei in Shaka Player abzuspielen:

  1. Machen Sie den von Ihnen erstellten Cloud Storage-Bucket öffentlich.
  2. So aktivieren Sie Cross-Origin Resource Sharing (CORS) für einen Cloud Storage-Bucket:
    1. Erstellen Sie eine JSON-Datei, die Folgendes enthält:
      [
        {
          "origin": ["https://shaka-player-demo.appspot.com/"],
          "responseHeader": ["Content-Type", "Range"],
          "method": ["GET", "HEAD"],
          "maxAgeSeconds": 3600
        }
      ]
    2. Führen Sie den folgenden Befehl aus, nachdem Sie JSON_FILE_NAME durch den Namen der JSON-Datei, die Sie im vorherigen Schritt erstellt haben:
      gsutil cors set JSON_FILE_NAME.json gs://BUCKET_NAME
  3. Suchen Sie im Cloud Storage-Bucket nach dem generierten main.m3u8 -Datei. Klicken Sie in der Spalte Öffentlicher Zugriff der Datei auf URL kopieren.
  4. Rufen Sie Shaka Player, ein Online-Livestream-Player, auf.
  5. Klicken Sie in der Navigationsleiste oben auf Benutzerdefinierte Inhalte.
  6. Klicken Sie auf die Schaltfläche +.
  7. Fügen Sie die öffentliche URL der Datei in das Feld URL manifestieren ein.

  8. Geben Sie einen Namen in das Feld Name ein.

  9. Klicken Sie auf Speichern.

  10. Klicken Sie auf Wiedergabe.

Während des Livestreams sollte ein Testmuster wiedergegeben werden.

Video zum Testen des Musters

Eine Werbeunterbrechungsmarkierung im Livestream hinzufügen

Verwenden Sie die Methode projects.locations.channels.events.create , um dem Livestream eine Werbeunterbrechungsmarkierung hinzuzufügen.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal
  • EVENT_ID: eine benutzerdefinierte Kennung für das Ereignis

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID/events/EVENT_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "adBreak": {
    "duration": "100s"
  },
  "executeNow": true,
  "state": "PENDING"
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Video.LiveStream.V1;

public class CreateChannelEventSample
{
    public Event CreateChannelEvent(
         string projectId, string locationId, string channelId, string eventId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        CreateEventRequest request = new CreateEventRequest
        {
            ParentAsChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId),
            EventId = eventId,
            Event = new Event
            {
                AdBreak = new Event.Types.AdBreakTask
                {
                    Duration = new Google.Protobuf.WellKnownTypes.Duration
                    {
                        Seconds = 30
                    }
                },
                ExecuteNow = true
            }
        };

        // Make the request.
        Event response = client.CreateEvent(request);
        return response;
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

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

// createChannelEvent creates a channel event. An event is a sub-resource of a
// channel, which can be scheduled by the user to execute operations on a
// channel resource without having to stop the channel. This sample creates an
// ad break event.
func createChannelEvent(w io.Writer, projectID, location, channelID, eventID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// eventID := "my-channel-event"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.CreateEventRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s/channels/%s", projectID, location, channelID),
		EventId: eventID,
		Event: &livestreampb.Event{
			Task: &livestreampb.Event_AdBreak{
				AdBreak: &livestreampb.Event_AdBreakTask{
					Duration: &duration.Duration{
						Seconds: 30,
					},
				},
			},
			ExecuteNow: true,
		},
	}
	// Creates the channel event.
	response, err := client.CreateEvent(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateEvent: %w", err)
	}

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

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.video.livestream.v1.ChannelName;
import com.google.cloud.video.livestream.v1.CreateEventRequest;
import com.google.cloud.video.livestream.v1.Event;
import com.google.cloud.video.livestream.v1.Event.AdBreakTask;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateChannelEvent {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String channelId = "my-channel-id";
    String eventId = "my-channel-event-id";

    createChannelEvent(projectId, location, channelId, eventId);
  }

  public static void createChannelEvent(
      String projectId, String location, String channelId, String eventId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var createEventRequest =
          CreateEventRequest.newBuilder()
              .setParent(ChannelName.of(projectId, location, channelId).toString())
              .setEventId(eventId)
              .setEvent(
                  Event.newBuilder()
                      .setAdBreak(
                          AdBreakTask.newBuilder()
                              .setDuration(Duration.newBuilder().setSeconds(30).build())
                              .build())
                      .setExecuteNow(true)
                      .build())
              .build();

      Event response = livestreamServiceClient.createEvent(createEventRequest);
      System.out.println("Channel event: " + response.getName());
    }
  }
}

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

async function createChannelEvent() {
  // Construct request
  const request = {
    parent: livestreamServiceClient.channelPath(
      projectId,
      location,
      channelId
    ),
    eventId: eventId,
    event: {
      adBreak: {
        duration: {
          seconds: 30,
        },
      },
      executeNow: true,
    },
  };

  // Run request
  const [event] = await livestreamServiceClient.createEvent(request);
  console.log(`Channel event: ${event.name}`);
}

createChannelEvent();

PHP

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Video\LiveStream\V1\Event;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\CreateEventRequest;
use Google\Protobuf\Duration;

/**
 * Creates a channel event. This particular sample inserts an ad break marker.
 * Other event types are supported.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 * @param string  $eventId            The ID of the channel event
 */
function create_channel_event(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $eventId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

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

    $eventAdBreak = (new Event\AdBreakTask())
        ->setDuration(new Duration(['seconds' => 30]));
    $event = (new Event())
        ->setAdBreak($eventAdBreak)
        ->setExecuteNow(true);

    // Run the channel event creation request.
    $request = (new CreateEventRequest())
        ->setParent($parent)
        ->setEvent($event)
        ->setEventId($eventId);
    $response = $livestreamClient->createEvent($request);
    // Print results.
    printf('Channel event: %s' . PHP_EOL, $response->getName());
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import argparse

from google.cloud.video import live_stream_v1
from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)
from google.protobuf import duration_pb2 as duration


def create_channel_event(
    project_id: str, location: str, channel_id: str, event_id: str
) -> live_stream_v1.types.Event:
    """Creates a channel event.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID.
        event_id: The user-defined event ID."""

    client = LivestreamServiceClient()
    parent = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}/events/{event_id}"

    event = live_stream_v1.types.Event(
        name=name,
        ad_break=live_stream_v1.types.Event.AdBreakTask(
            duration=duration.Duration(
                seconds=30,
            ),
        ),
        execute_now=True,
    )

    response = client.create_event(parent=parent, event=event, event_id=event_id)
    print(f"Channel event: {response.name}")

    return response

Ruby

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "google/cloud/video/live_stream"

##
# Create a channel event
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param channel_id [String] Your channel name (e.g. "my-channel")
# @param event_id [String] Your event name (e.g. "my-event")
#
def create_channel_event project_id:, location:, channel_id:, event_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the parent.
  parent = client.channel_path project: project_id, location: location, channel: channel_id

  # Set the event fields.
  new_event = {
    ad_break: {
      duration: {
        seconds: 100
      }
    },
    execute_now: true
  }

  response = client.create_event parent: parent, event: new_event, event_id: event_id

  # Print the channel event name.
  puts "Channel event: #{response.name}"
end

Prüfen, ob die Markierung für eine Werbeunterbrechung vorhanden ist

Wenn die Anzeigenmarkierung in den Livestream eingefügt wird, erscheint ein Ereignis mit der Bezeichnung CUE-OUT ist im HLS-Manifest für die angegebene Anzeige zu sehen Dauer (100 Sek.)

Führen Sie den folgenden Befehl aus, um den Inhalt des generierten HLS-Manifests anzuzeigen:

gsutil cat gs://BUCKET_NAME/mux_video_ts/index-1.m3u8

Möglicherweise müssen Sie den Befehl gsutil cat mehrmals ausführen, bis der Der Abschnitt CUE-OUT wird angezeigt:

...
#EXTM3U
#EXT-X-VERSION:7
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:40
#EXT-X-DISCONTINUITY-SEQUENCE:0
#EXT-X-CUE-OUT:100.000000
#EXT-X-PROGRAM-DATE-TIME:2021-07-13T19:11:49.956Z
#EXTINF:2.000000
segment-0000000040.ts
#EXT-X-CUE-OUT-CONT:ElapsedTime=2.000000,Duration=100.000000
#EXT-X-PROGRAM-DATE-TIME:2021-07-13T19:11:51.956Z
#EXTINF:2.000000
segment-0000000041.ts
#EXT-X-CUE-OUT-CONT:ElapsedTime=4.000000,Duration=100.000000
#EXT-X-PROGRAM-DATE-TIME:2021-07-13T19:11:53.956Z
#EXTINF:2.000000
segment-0000000042.ts
#EXT-X-CUE-OUT-CONT:ElapsedTime=6.000000,Duration=100.000000
#EXT-X-PROGRAM-DATE-TIME:2021-07-13T19:11:55.956Z
#EXTINF:2.000000
segment-0000000043.ts
#EXT-X-CUE-OUT-CONT:ElapsedTime=8.000000,Duration=100.000000
...

Bereinigen

Mit den folgenden Schritten vermeiden Sie, dass Ihrem Google Cloud-Konto die in dieser Anleitung verwendeten Ressourcen in Rechnung gestellt werden:

Kanal beenden

Verwenden Sie die Methode projects.locations.channels.stop um den Kanal zu beenden. Du musst den Kanal erst beenden, bevor du ihn löschen kannst.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
    "verb": "stop",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Verwenden Sie OPERATION_ID, um den Vorgang zu prüfen. Status, bis "done":true im Ergebnis angezeigt wird.

Eingabestream beenden

Wenn Sie ffmpeg zum Senden des Eingabestreams verwendet haben, wird die Verbindung automatisch hergestellt. nachdem du den Kanal beendet hast.

Wenn du andere Encoder mit Wiederholungsmechanismen verwendet hast, musst du den Vorgang möglicherweise manuell beenden. des Eingabestreams.

Termin löschen

Verwenden Sie die Methode projects.locations.channels.events.delete um das Ereignis für die Werbeunterbrechung zu löschen. Du musst Kanalereignisse löschen, bevor du können den Kanal löschen.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal
  • EVENT_ID: eine benutzerdefinierte Kennung für das Ereignis

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Video.LiveStream.V1;

public class DeleteChannelEventSample
{
    public void DeleteChannelEvent(
         string projectId, string locationId, string channelId, string eventId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        DeleteEventRequest request = new DeleteEventRequest
        {
            EventName = EventName.FromProjectLocationChannelEvent(projectId, locationId, channelId, eventId),
        };

        // Make the request.
        client.DeleteEvent(request);
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

// deleteChannelEvent deletes a previously-created channel event.
func deleteChannelEvent(w io.Writer, projectID, location, channelID, eventID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// channelID := "my-channel"
	// eventID := "my-channel-event"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.DeleteEventRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/channels/%s/events/%s", projectID, location, channelID, eventID),
	}

	err = client.DeleteEvent(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteEvent: %w", err)
	}

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

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.video.livestream.v1.DeleteEventRequest;
import com.google.cloud.video.livestream.v1.EventName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import java.io.IOException;

public class DeleteChannelEvent {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String channelId = "my-channel-id";
    String eventId = "my-channel-event-id";

    deleteChannelEvent(projectId, location, channelId, eventId);
  }

  public static void deleteChannelEvent(
      String projectId, String location, String channelId, String eventId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      var deleteEventRequest =
          DeleteEventRequest.newBuilder()
              .setName(EventName.of(projectId, location, channelId, eventId).toString())
              .build();

      livestreamServiceClient.deleteEvent(deleteEventRequest);
      System.out.println("Deleted channel event");
    }
  }
}

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

async function deleteChannelEvent() {
  // Construct request
  const request = {
    name: livestreamServiceClient.eventPath(
      projectId,
      location,
      channelId,
      eventId
    ),
  };

  // Run request
  await livestreamServiceClient.deleteEvent(request);
  console.log('Deleted channel event');
}

deleteChannelEvent();

PHP

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\DeleteEventRequest;

/**
 * Deletes a channel event.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 * @param string  $eventId            The ID of the channel event to be deleted
 */
function delete_channel_event(
    string $callingProjectId,
    string $location,
    string $channelId,
    string $eventId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $formattedName = $livestreamClient->eventName($callingProjectId, $location, $channelId, $eventId);

    // Run the channel event deletion request.
    $request = (new DeleteEventRequest())
        ->setName($formattedName);
    $livestreamClient->deleteEvent($request);
    printf('Deleted channel event %s' . PHP_EOL, $eventId);
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import argparse

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


def delete_channel_event(
    project_id: str, location: str, channel_id: str, event_id: str
) -> None:
    """Deletes a channel event.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID.
        event_id: The user-defined event ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}/events/{event_id}"
    response = client.delete_event(name=name)
    print("Deleted channel event")

    return response

Ruby

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "google/cloud/video/live_stream"

##
# Delete a channel event
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param channel_id [String] Your channel name (e.g. "my-channel")
# @param event_id [String] Your event name (e.g. "my-event")
#
def delete_channel_event project_id:, location:, channel_id:, event_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the channel event.
  name = client.event_path project: project_id, location: location, channel: channel_id, event: event_id

  # Delete the channel event.
  client.delete_event name: name

  # Print a success message.
  puts "Deleted channel event"
end

Den Kanal löschen

Verwenden Sie die Methode projects.locations.channels.delete um den Kanal zu löschen. Du musst den Kanal vor dem Löschen löschen den vom Kanal verwendeten Eingabeendpunkt.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich dein Kanal befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • 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: eine benutzerdefinierte Kennung für den Kanal

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
    "verb": "delete",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Verwenden Sie OPERATION_ID, um den Vorgang zu prüfen. Status, bis "done":true im Ergebnis angezeigt wird.

Eingabeendpunkt löschen

Verwenden Sie die Methode projects.locations.inputs.delete zum Löschen des Eingabeendpunkts.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_NUMBER: Ihr Google Cloud-Projekt Zahl; Sie finden sie im Feld Projektnummer auf der Seite IAM-Einstellungen
  • LOCATION: der Ort, an dem sich der Eingabeendpunkt befindet gefunden; eine der unterstützten Regionen verwenden
    Standorte anzeigen
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID: die benutzerdefinierte Kennung für den Eingabeendpunkt

Wenn Sie die Anfrage senden möchten, maximieren Sie eine der folgenden Optionen:

Sie sollten in etwa folgende JSON-Antwort erhalten:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.video.livestream.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID",
    "verb": "delete",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – C# API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Video.LiveStream.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class DeleteInputSample
{
    public async Task DeleteInputAsync(
         string projectId, string locationId, string inputId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        DeleteInputRequest request = new DeleteInputRequest
        {
            InputName = InputName.FromProjectLocationInput(projectId, locationId, inputId)
        };

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

        // Poll until the returned long-running operation is complete.
        await response.PollUntilCompletedAsync();
    }
}

Go

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Go API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

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

// deleteInput deletes a previously-created input endpoint.
func deleteInput(w io.Writer, projectID, location, inputID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputID := "my-input"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.DeleteInputRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
	}

	op, err := client.DeleteInput(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteInput: %w", err)
	}
	err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

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

Java

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Java API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.video.livestream.v1.DeleteInputRequest;
import com.google.cloud.video.livestream.v1.InputName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteInput {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String inputId = "my-input-id";

    deleteInput(projectId, location, inputId);
  }

  public static void deleteInput(String projectId, String location, String inputId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    var deleteInputRequest =
        DeleteInputRequest.newBuilder()
            .setName(InputName.of(projectId, location, inputId).toString())
            .build();
    // First API call in a project can take up to 10 minutes.
    livestreamServiceClient.deleteInputAsync(deleteInputRequest).get(10, TimeUnit.MINUTES);
    System.out.println("Deleted input");
    livestreamServiceClient.close();
  }
}

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Node.js API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

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

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

async function deleteInput() {
  // Construct request
  const request = {
    name: livestreamServiceClient.inputPath(projectId, location, inputId),
  };

  // Run request
  const [operation] = await livestreamServiceClient.deleteInput(request);
  await operation.promise();
  console.log('Deleted input');
}

deleteInput();

PHP

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – PHP API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\DeleteInputRequest;

/**
 * Deletes an input.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the input
 * @param string  $inputId            The ID of the input to be deleted
 */
function delete_input(
    string $callingProjectId,
    string $location,
    string $inputId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $formattedName = $livestreamClient->inputName($callingProjectId, $location, $inputId);

    // Run the input deletion request. The response is a long-running operation ID.
    $request = (new DeleteInputRequest())
        ->setName($formattedName);
    $operationResponse = $livestreamClient->deleteInput($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print status
        printf('Deleted input %s' . PHP_EOL, $inputId);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Python API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import argparse

from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)
from google.protobuf import empty_pb2 as empty


def delete_input(project_id: str, location: str, input_id: str) -> empty.Empty:
    """Deletes an input.
    Args:
        project_id: The GCP project ID.
        location: The location of the input.
        input_id: The user-defined input ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/inputs/{input_id}"
    operation = client.delete_input(name=name)
    response = operation.result(600)
    print("Deleted input")

    return response

Ruby

Informationen zum Installieren und Verwenden der Clientbibliothek für die Live Stream API findest du unter Live Stream API-Clientbibliotheken Weitere Informationen finden Sie in der Live Stream API – Ruby API Referenzdokumentation.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei der Live Stream API zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "google/cloud/video/live_stream"

##
# Delete an input endpoint
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param input_id [String] Your input name (e.g. "my-input")
#
def delete_input project_id:, location:, input_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

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

  # Delete the input.
  operation = client.delete_input name: name

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print a success message.
  puts "Deleted input"
end

Cloud Storage-Bucket löschen

Alle Dateien und Ordner im Bucket, die von der Live Stream API generiert wurden, werden gelöscht, sobald du den Kanal beendest.

  1. Rufen Sie in der Google Cloud Console den Cloud Storage-Browser auf.

    Zum Cloud Storage-Browser

  2. Klicken Sie das Kästchen neben dem von Ihnen erstellten Bucket an.

  3. Klicken Sie auf Löschen.

  4. Klicken Sie im angezeigten Pop-up-Fenster auf Löschen, um den Bucket und seine Inhalte endgültig zu löschen.

Anmeldedaten widerrufen

  1. Optional: Widerrufen Sie die von Ihnen erstellten Anmeldedaten für die Authentifizierung und löschen Sie die lokale Datei mit den Anmeldedaten:

    gcloud auth application-default revoke
  2. Optional: Widerrufen Sie Anmeldedaten von der gcloud-CLI.

    gcloud auth revoke

Nächste Schritte