מדריך מהיר לשידור חי בפורמט MPEG-DASH

בדף הזה מוסבר איך ליצור משימת סטרימינג בשידור חי בפורמט MPEG-DASH באמצעות הגדרות ברירת המחדל של Live Stream API ו-curl,‏ PowerShell או ספריות הלקוח.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. התקינו את ה-CLI של Google Cloud.

  3. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  4. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  5. יוצרים או בוחרים Google Cloud פרויקט.

    תפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • Select a project: כדי לבחור פרויקט לא צריך תפקיד IAM ספציפי – אפשר לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד Project Creator (יצירת פרויקטים) (roles/resourcemanager.projectCreator), שכולל את ההרשאה resourcemanager.projects.create. איך מקצים תפקידים
    • יוצרים Google Cloud פרויקט:

      gcloud projects create PROJECT_ID

      מחליפים את PROJECT_ID בשם של פרויקט Google Cloud שיוצרים.

    • בוחרים את הפרויקט שיצרתם: Google Cloud

      gcloud config set project PROJECT_ID

      מחליפים את PROJECT_ID בשם הפרויקט ב- Google Cloud .

  6. מוודאים שהחיוב מופעל בפרויקט Google Cloud .

  7. מפעילים את Live Stream API:

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    gcloud services enable livestream.googleapis.com
  8. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  9. מעניקים תפקידים לחשבון המשתמש. מריצים את הפקודה הבאה לכל אחד מהתפקידים הבאים ב-IAM: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט.
    • USER_IDENTIFIER: המזהה של חשבון המשתמש . לדוגמה, myemail@example.com.
    • ROLE: תפקיד ה-IAM שאתם מקצים לחשבון המשתמש.
  10. התקינו את ה-CLI של Google Cloud.

  11. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  12. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  13. יוצרים או בוחרים Google Cloud פרויקט.

    תפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • Select a project: כדי לבחור פרויקט לא צריך תפקיד IAM ספציפי – אפשר לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד Project Creator (יצירת פרויקטים) (roles/resourcemanager.projectCreator), שכולל את ההרשאה resourcemanager.projects.create. איך מקצים תפקידים
    • יוצרים Google Cloud פרויקט:

      gcloud projects create PROJECT_ID

      מחליפים את PROJECT_ID בשם של פרויקט Google Cloud שיוצרים.

    • בוחרים את הפרויקט שיצרתם: Google Cloud

      gcloud config set project PROJECT_ID

      מחליפים את PROJECT_ID בשם הפרויקט ב- Google Cloud .

  14. מוודאים שהחיוב מופעל בפרויקט Google Cloud .

  15. מפעילים את Live Stream API:

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    gcloud services enable livestream.googleapis.com
  16. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  17. מעניקים תפקידים לחשבון המשתמש. מריצים את הפקודה הבאה לכל אחד מהתפקידים הבאים ב-IAM: roles/livestream.editor, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט.
    • USER_IDENTIFIER: המזהה של חשבון המשתמש . לדוגמה, myemail@example.com.
    • ROLE: תפקיד ה-IAM שאתם מקצים לחשבון המשתמש.

יצירת קטגוריה של Cloud Storage

יוצרים קטגוריה של Cloud Storage כדי לאחסן את קובץ המניפסט והפלחים של השידור החי.

מסוףGoogle Cloud

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. לוחצים על יצירה.
  3. ממלאים את פרטי הקטגוריה בדף Create a bucket. כדי לעבור לשלב הבא לוחצים על Continue.
    1. בקטע Get started (תחילת העבודה), מבצעים את הפעולות הבאות:
    2. בקטע Choose where to store your data, מבצעים את הפעולות הבאות:
      1. בוחרים סוג מיקום.
      2. בתפריט הנפתח Location type, בוחרים מיקום שבו יישמרו נתוני הקטגוריה באופן קבוע.
      3. כדי להגדיר שכפול בין מאגרי מידע, בוחרים באפשרות הוספת שכפול בין מאגרי מידע באמצעות Storage Transfer Service ופועלים לפי השלבים הבאים:

        הגדרה של רפליקציה בין מאגרי מידע

        1. בתפריט Bucket, בוחרים באפשרות הרצויה.
        2. בקטע הגדרות השכפול, לוחצים על הגדרה כדי להגדיר את ההגדרות של משימת השכפול.

          מופיעה החלונית Configure cross-bucket replication.

          • כדי לסנן אובייקטים לשכפול לפי קידומת של שם האובייקט, מזינים קידומת שרוצים לכלול או להחריג אובייקטים ממנה, ואז לוחצים על הוספת קידומת.
          • כדי להגדיר סוג אחסון לאובייקטים המשוכפלים, בוחרים סוג אחסון בתפריט סוג אחסון. אם מדלגים על השלב הזה, האובייקטים המשוכפלים ישתמשו בסוג האחסון של קטגוריית היעד כברירת מחדל.
          • לוחצים על סיום.
    3. בקטע Choose how to store your data, מבצעים את הפעולות הבאות:
      1. בקטע Set a default class, בוחרים באפשרות הבאה: Standard.
      2. כדי להפעיל מרחב שמות היררכי, בקטע Optimize storage for data-intensive workloads, בוחרים באפשרות Enable hierarchical namespace on this bucket.
    4. בקטע Choose how to control access to objects, בוחרים אם הקטגוריה אוכפת public access prevention או לא, ואז בוחרים שיטת בקרת גישה לאובייקטים של הקטגוריה.
    5. בקטע Choose how to protect object data, מבצעים את הפעולות הבאות:
      • בוחרים באחת מהאפשרויות בקטע הגנה על נתונים שרוצים להגדיר לקטגוריה.
        • כדי להפעיל מחיקה עם יכולת שחזור, מסמנים את התיבה מדיניות מחיקה עם יכולת שחזור (לשחזור נתונים) ומציינים את מספר הימים שבהם רוצים לשמור אובייקטים אחרי המחיקה.
        • כדי להגדיר ניהול גרסאות של אובייקטים, מסמנים את התיבה ניהול גרסאות של אובייקטים (לשליטה בגרסאות) ומציינים את מספר הגרסאות המקסימלי לכל אובייקט ואת מספר הימים שאחריהם הגרסאות הלא עדכניות יפוגו.
        • כדי להפעיל את מדיניות שמירת הנתונים על אובייקטים וקטגוריות, לוחצים על תיבת הסימון שמירת נתונים (לצורך תאימות), ואז מבצעים את הפעולות הבאות:
          • כדי להפעיל את הנעילה של שמירת אובייקטים, מסמנים את התיבה הפעלת שמירת אובייקטים.
          • כדי להפעיל את נעילת הקטגוריה, מסמנים את תיבת הסימון הגדרת מדיניות שמירת נתונים בקטגוריה ובוחרים יחידת זמן ואת משך הזמן של תקופת השמירה.
      • כדי לבחור איך להצפין את נתוני האובייקט, מרחיבים את הקטע Data encryption () ובוחרים Data encryption method.
  4. לוחצים על יצירה.

שורת הפקודה

    יוצרים קטגוריה של Cloud Storage:
    gcloud storage buckets create gs://BUCKET_NAME
    מחליפים את BUCKET_NAME בשם קטגוריה שעומד בקריטריונים לשמות של קטגוריות.

התקנת מקודד

כדי להשתמש ב-API, צריך מקודד שיצור זרמי קלט שה-API יעבד.

כדאי להתקין את ffmpeg כי בדף הזה מוסבר איך להשתמש ב-ffmpeg כדי ליצור זרמי קלט. אפשר להתקין אותו ב-Cloud Shell באמצעות הפקודה הבאה.

sudo apt install ffmpeg

יצירת נקודת קצה לקלט

כדי להתחיל שידור חי, קודם צריך להשתמש בשיטה projects.locations.inputs.create כדי ליצור נקודת קצה של קלט. אתם שולחים את זרם הקלט לנקודת הקצה הזו.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו רוצים ליצור את נקודת הקצה של הקלט. צריך להשתמש באחד מהאזורים הנתמכים
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID: מזהה שמוגדר על ידי המשתמש לנקודת הקצה החדשה של הקלט שצריך ליצור (שאליה שולחים את זרם הקלט). הערך הזה צריך לכלול בין 1 ל-63 תווים, להתחיל ולהסתיים ב-[a-z0-9], ויכול לכלול מקפים (-) בין התווים. לדוגמה, my-input.

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

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

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

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

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class CreateInput {

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

    createInput(projectId, location, inputId);
  }

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

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

createInput();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


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

    client = LivestreamServiceClient()

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

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

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

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

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

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

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

מעתיקים את הערך OPERATION_ID שמוחזר כדי להשתמש בו בקטע הבא.

בדיקת התוצאה

משתמשים בשיטה projects.locations.operations.get כדי לבדוק אם נקודת הקצה של הקלט נוצרה. אם התשובה מכילה את הערך "done: false", חוזרים על הפקודה עד שהתשובה מכילה את הערך "done: true". יצירת נקודת הקצה הראשונה לקלט באזור מסוים עשויה להימשך עד 10 דקות.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום של נקודת הקצה של הקלט. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • OPERATION_ID: המזהה של הפעולה

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

מחפשים את השדה uri ומעתיקים את הערך INPUT_STREAM_URI שמוחזר כדי להשתמש בו בהמשך בקטע שליחת זרם הקלט.

יצירת ערוץ

כדי לבצע טרנסקוד של זרם הקלט לזרם פלט, צריך ליצור משאב של ערוץ.

כדי ליצור ערוץ, משתמשים ב-method‏ projects.locations.channels.create. בדוגמה הבאה נוצר ערוץ שמפיק שידור חי בפורמט MPEG-DASH שכולל עיבוד יחיד ברזולוציה גבוהה (1280x720).

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו רוצים ליצור את הערוץ. צריך להשתמש באחד האזורים הנתמכים
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ שרוצים ליצור. הערך הזה צריך להיות באורך של 1-63 תווים, להתחיל ולהסתיים ב-[a-z0-9], ויכול להכיל מקפים (-) בין התווים
  • INPUT_ID: המזהה שמוגדר על ידי המשתמש לנקודת הקצה של הקלט
  • BUCKET_NAME: השם של קטגוריית Cloud Storage שיצרתם כדי לאחסן את קובצי המניפסט והפלחים של השידור החי

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

קבלת הערוץ

אפשר לבדוק את התוצאה של פעולת יצירת הערוץ באמצעות מזהה הפעולה החדש.

אחרי שיוצרים את הערוץ, משתמשים בשיטה projects.locations.channels.get כדי לשלוח שאילתה לגבי מצב הערוץ.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/channels/CHANNEL_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "inputAttachments": [
    {
      "key": "INPUT_ID",
      "input": "projects/PROJECT_NUMBER/locations/LOCATION/inputs/INPUT_ID"
    }
  ],
  "activeInput": "INPUT_ID",
  "output": {
    "uri": "gs://BUCKET_NAME"
  },
  "elementaryStreams": [
    {
      "videoStream": {
        "h264": {
          "widthPixels": 1280,
          "heightPixels": 720,
          "frameRate": 30,
          "bitrateBps": 3000000,
          "gopDuration": "2s",
          "vbvSizeBits": 3000000,
          "vbvFullnessBits": 2700000,
          "entropyCoder": "cabac",
          "profile": "high"
        }
      },
      "key": "es_video"
    },
    {
      "audioStream": {
        "codec": "aac",
        "bitrateBps": 160000,
        "channelCount": 2,
        "channelLayout": ["fl", "fr"],
        "sampleRateHertz": 48000
      },
      "key": "es_audio"
    }
  ],
  "muxStreams": [
    {
      "key": "mux_video",
      "container": "fmp4",
      "elementaryStreams": ["es_video"],
      "segmentSettings": { "segmentDuration": "2s" }
    },
    {
      "key": "mux_audio",
      "container": "fmp4",
      "elementaryStreams": ["es_audio"],
      "segmentSettings": { "segmentDuration": "2s" }
    }
  ],
  "manifests": [
    {
      "key": "manifest_dash",
      "fileName": "main.mpd",
      "type": "DASH",
      "muxStreams": [
        "mux_video",
        "mux_audio"
      ],
      "maxSegmentCount": 5,
      "segmentKeepDuration": "60s"
    }
  ],
  "streamingState": "STOPPED"
}

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Video.LiveStream.V1;

public class GetChannelSample
{
    public Channel GetChannel(
         string projectId, string locationId, string channelId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        GetChannelRequest request = new GetChannelRequest
        {
            ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
        };

        // Make the request.
        Channel response = client.GetChannel(request);
        return response;
    }
}

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class GetChannel {

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

    getChannel(projectId, location, channelId);
  }

  public static void getChannel(String projectId, String location, String channelId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      ChannelName name = ChannelName.of(projectId, location, channelId);
      Channel response = livestreamServiceClient.getChannel(name);
      System.out.println("Channel: " + response.getName());
    }
  }
}

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

async function getChannel() {
  // Construct request
  const request = {
    name: livestreamServiceClient.channelPath(projectId, location, channelId),
  };
  const [channel] = await livestreamServiceClient.getChannel(request);
  console.log(`Channel: ${channel.name}`);
}

getChannel();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

/**
 * Gets a channel.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 */
function get_channel(
    string $callingProjectId,
    string $location,
    string $channelId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);

    // Get the channel.
    $request = (new GetChannelRequest())
        ->setName($formattedName);
    $response = $livestreamClient->getChannel($request);
    // Print results
    printf('Channel: %s' . PHP_EOL, $response->getName());
}

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


def get_channel(
    project_id: str, location: str, channel_id: str
) -> live_stream_v1.types.Channel:
    """Gets a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    response = client.get_channel(name=name)
    print(f"Channel: {response.name}")

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

  # Get the channel.
  channel = client.get_channel name: name

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

התשובה המלאה מכילה את השדה הבא. (חלק מדוגמאות הקוד שלמעלה מחזירות רק שדות מסוימים בתשובה, אבל אפשר לשנות אותן כדי לקבל את התשובה המלאה).

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

התשובה הזו מציינת שעכשיו אפשר להתחיל את הערוץ.

הפעלת הערוץ

משתמשים ב-method‏ projects.locations.channels.start כדי להפעיל את הערוץ. צריך להפעיל ערוץ לפני שאפשר לקבל ממנו זרמי קלט או ליצור ממנו זרם פלט.

הפעלת הערוץ הראשון באזור מסוים אורכת כ-10 דקות.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class StartChannelSample
{
    public async Task StartChannelAsync(
         string projectId, string locationId, string channelId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        StartChannelRequest request = new StartChannelRequest
        {
            ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
        };

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class StartChannel {

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

    startChannel(projectId, location, channelId);
  }

  public static void startChannel(String projectId, String location, String channelId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    ChannelName name = ChannelName.of(projectId, location, channelId);
    // First API call in a project can take up to 15 minutes.
    livestreamServiceClient.startChannelAsync(name).get(15, TimeUnit.MINUTES);
    System.out.println("Started channel");
    livestreamServiceClient.close();
  }
}

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

async function startChannel() {
  // Construct request
  const request = {
    name: livestreamServiceClient.channelPath(projectId, location, channelId),
  };
  const [operation] = await livestreamServiceClient.startChannel(request);
  await operation.promise();
  console.log('Started channel');
}

startChannel();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

/**
 * Starts a channel.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 */
function start_channel(
    string $callingProjectId,
    string $location,
    string $channelId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);

    // Run the channel start request. The response is a long-running operation ID.
    $request = (new StartChannelRequest())
        ->setName($formattedName);
    $operationResponse = $livestreamClient->startChannel($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print results
        printf('Started channel' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


def start_channel(
    project_id: str, location: str, channel_id: str
) -> live_stream_v1.types.ChannelOperationResponse:
    """Starts a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    operation = client.start_channel(name=name)
    response = operation.result(900)
    print("Started channel")

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

  # Start the channel.
  operation = client.start_channel name: name

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

  # Print a success message.
  puts "Started channel"
end

שליחת זרם הקלט

כדי לבדוק אם הערוץ הופעל, מקבלים את פרטי הערוץ כמו שמתואר למעלה. התשובה צריכה לכלול את הפרטים הבאים:

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

אחרי שהערוץ מוכן, שולחים זרם קלט לבדיקה לנקודת הקצה של הקלט כדי ליצור את השידור החי.

פותחים חלון טרמינל חדש. מריצים את הפקודה הבאה, באמצעות INPUT_STREAM_URI מהקטע בדיקת התוצאה:

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

איך בודקים אם הערוץ משדר

כדי לבדוק את הסטטוס של פעולת הסטרימינג בשידור חי, מקבלים את פרטי הערוץ כמו שמתואר למעלה. התשובה צריכה לכלול את הפרטים הבאים:

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

אימות התוכן בקטגוריה של Cloud Storage

פותחים את הקטגוריה של Cloud Storage. מוודאים שהוא מכיל את הקבצים והספריות הבאים:

  • main.mpd
  • mux_audio/
    • כמה קבצים segment-segment-number.m4s
    • קובץ segment-initialization_segment_0000000000.m4s אחד
  • mux_video/
    • כמה קבצים segment-segment-number.m4s
    • קובץ segment-initialization_segment_0000000000.m4s אחד

הפעלת השידור החי שנוצר

כדי להפעיל את קובץ המדיה שנוצר ב-Shaka Player, מבצעים את השלבים הבאים:

  1. הפיכת הקטגוריה של Cloud Storage שיצרתם לקריאה באופן ציבורי.
  2. כדי להפעיל שיתוף משאבים בין מקורות (CORS) בקטגוריה של Cloud Storage, מבצעים את הפעולות הבאות:
    1. יוצרים קובץ JSON שמכיל את הפרטים הבאים:
      [
        {
          "origin": ["https://shaka-player-demo.appspot.com/"],
          "responseHeader": ["Content-Type", "Range"],
          "method": ["GET", "HEAD"],
          "maxAgeSeconds": 3600
        }
      ]
    2. מריצים את הפקודה הבאה אחרי שמחליפים את JSON_FILE_NAME בשם של קובץ ה-JSON שיצרתם בשלב הקודם:
      gcloud storage buckets update gs://BUCKET_NAME --cors-file=JSON_FILE_NAME.json
  3. בקטגוריה של Cloud Storage, מוצאים את הקובץ main.mpd שנוצר. לוחצים על העתקת כתובת URL בעמודה גישה ציבורית של הקובץ.
  4. עוברים אל Shaka Player, נגן שידורים חיים באינטרנט.
  5. בסרגל הניווט העליון, לוחצים על תוכן בהתאמה אישית.
  6. לוחצים על הלחצן +.
  7. מדביקים את כתובת ה-URL הציבורית של הקובץ בתיבה Manifest URL (כתובת ה-URL של קובץ המניפסט).

  8. מקלידים שם בתיבה שם.

  9. לוחצים על Save.

  10. לוחצים על הפעלה.

תבנית בדיקה תופעל כשידור חי.

סרטון עם דפוס בדיקה

הוספת סמן להפסקה למודעה לשידור החי

משתמשים בשיטה projects.locations.channels.events.create כדי להוסיף סמן להפסקה למודעה לשידור החי.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ
  • EVENT_ID: מזהה שהוגדר על ידי המשתמש לאירוע

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Video.LiveStream.V1;

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

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class CreateChannelEvent {

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

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

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

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

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

createChannelEvent();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


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

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

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

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

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

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

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

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

מוודאים שסמן הפסקה למודעה קיים

כשסמן הפרסומת מוכנס לשידור החי, אירוע עם התווית <SpliceInfoSection> מופיע במניפסט DASH למשך הפרסומת שצוין (100 שניות).

מריצים את הפקודה הבאה כדי לראות את התוכן של מניפסט DASH שנוצר:

gcloud storage cat gs://BUCKET_NAME/main.mpd

יכול להיות שתצטרכו להריץ את הפקודה gcloud storage cat כמה פעמים עד שהקטע <SpliceInfoSection> יופיע:

<EventStream timescale="10000000" schemeIdUri="urn:scte:scte35:2013:xml">
  <Event duration="100000000" id="809">
    <SpliceInfoSection xmlns="urn:scte:scte35:2013:xml">
      <SpliceInsert outOfNetworkIndicator="true" spliceImmediateFlag="true">
        <BreakDuration autoReturn="true" duration="100000000"/>
      </SpliceInsert>
    </SpliceInfoSection>
  </Event>
</EventStream>

הסרת המשאבים

כדי לא לצבור חיובים לחשבון Google Cloud על המשאבים שבהם השתמשתם בדף הזה, פועלים לפי השלבים הבאים:

הפסקת הערוץ

משתמשים ב-method‏ projects.locations.channels.stop כדי להפסיק את הערוץ. כדי למחוק ערוץ, צריך קודם להפסיק אותו.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class StopChannelSample
{
    public async Task StopChannelAsync(
         string projectId, string locationId, string channelId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        StopChannelRequest request = new StopChannelRequest
        {
            ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
        };

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class StopChannel {

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

    stopChannel(projectId, location, channelId);
  }

  public static void stopChannel(String projectId, String location, String channelId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    ChannelName name = ChannelName.of(projectId, location, channelId);
    // First API call in a project can take up to 10 minutes.
    livestreamServiceClient.stopChannelAsync(name).get(10, TimeUnit.MINUTES);
    System.out.println("Stopped channel");
    livestreamServiceClient.close();
  }
}

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

async function stopChannel() {
  // Construct request
  const request = {
    name: livestreamServiceClient.channelPath(projectId, location, channelId),
  };
  const [operation] = await livestreamServiceClient.stopChannel(request);
  await operation.promise();
  console.log('Stopped channel');
}

stopChannel();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

/**
 * Stops a channel.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the channel
 * @param string  $channelId          The ID of the channel
 */
function stop_channel(
    string $callingProjectId,
    string $location,
    string $channelId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();
    $formattedName = $livestreamClient->channelName($callingProjectId, $location, $channelId);

    // Run the channel stop request. The response is a long-running operation ID.
    $request = (new StopChannelRequest())
        ->setName($formattedName);
    $operationResponse = $livestreamClient->stopChannel($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print results
        printf('Stopped channel' . PHP_EOL);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


def stop_channel(
    project_id: str, location: str, channel_id: str
) -> live_stream_v1.types.ChannelOperationResponse:
    """Stops a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    operation = client.stop_channel(name=name)
    response = operation.result(600)
    print("Stopped channel")

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

  # Stop the channel.
  operation = client.stop_channel name: name

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

  # Print a success message.
  puts "Stopped channel"
end

משתמשים ב-OPERATION_ID כדי לבדוק את סטטוס הפעולה עד שמקבלים "done":true בתוצאה.

הפסקת זרם הקלט

אם השתמשתם ב-ffmpeg כדי לשלוח את זרם הקלט, החיבור ינותק אוטומטית אחרי שתפסיקו את הערוץ.

אם השתמשתם במקודדים אחרים עם מנגנוני ניסיון חוזר, יכול להיות שתצטרכו להפסיק את זרם הקלט באופן ידני.

מחיקת האירוע

משתמשים בשיטה projects.locations.channels.events.delete כדי למחוק את אירוע ההפסקה למודעה. כדי למחוק את הערוץ, קודם צריך למחוק את האירועים שקשורים אליו.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ
  • EVENT_ID: מזהה שהוגדר על ידי המשתמש לאירוע

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Video.LiveStream.V1;

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

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class DeleteChannelEvent {

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

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

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

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

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

deleteChannelEvent();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


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

    client = LivestreamServiceClient()

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

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

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

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

מחיקת הערוץ

כדי למחוק את הערוץ, משתמשים בשיטה projects.locations.channels.delete. צריך למחוק את הערוץ לפני שמוחקים את נקודת הקצה של הקלט שבה הערוץ משתמש.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום שבו הערוץ נמצא. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • CHANNEL_ID: מזהה מוגדר על ידי המשתמש של הערוץ

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class DeleteChannelSample
{
    public async Task DeleteChannelAsync(
         string projectId, string locationId, string channelId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        DeleteChannelRequest request = new DeleteChannelRequest
        {
            ChannelName = ChannelName.FromProjectLocationChannel(projectId, locationId, channelId)
        };

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class DeleteChannel {

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

    deleteChannel(projectId, location, channelId);
  }

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

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

deleteChannel();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


def delete_channel(project_id: str, location: str, channel_id: str) -> empty.Empty:
    """Deletes a channel.
    Args:
        project_id: The GCP project ID.
        location: The location of the channel.
        channel_id: The user-defined channel ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/channels/{channel_id}"
    operation = client.delete_channel(name=name)
    response = operation.result(600)
    print("Deleted channel")

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

  # Delete the channel.
  operation = client.delete_channel name: name

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

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

משתמשים ב-OPERATION_ID כדי לבדוק את סטטוס הפעולה עד שמקבלים "done":true בתוצאה.

מחיקת נקודת הקצה של הקלט

כדי למחוק את נקודת הקצה של הקלט, משתמשים בשיטה projects.locations.inputs.delete.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_NUMBER: מספר הפרויקט שלכם. הוא מופיע בשדה מספר הפרויקט בדף הגדרות IAM. Google Cloud
  • LOCATION: המיקום של נקודת הקצה של הקלט. צריך להשתמש באחד מהאזורים הנתמכים.
    הצגת מיקומים
    • us-central1
    • us-east1
    • us-east4
    • us-west1
    • us-west2
    • northamerica-northeast1
    • southamerica-east1
    • asia-east1
    • asia-east2
    • asia-south1
    • asia-northeast1
    • asia-southeast1
    • australia-southeast1
    • europe-north1
    • europe-west1
    • europe-west2
    • europe-west3
    • europe-west4
  • INPUT_ID: המזהה שמוגדר על ידי המשתמש לנקודת הקצה של הקלט

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

C#

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API C# API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

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

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

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

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

Go

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Go API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Java

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Java API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public class DeleteInput {

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

    deleteInput(projectId, location, inputId);
  }

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

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Node.js API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

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

deleteInput();

PHP

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API PHP API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

Python

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Python API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import argparse

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


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

    client = LivestreamServiceClient()

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

    return response

Ruby

מידע על התקנה ושימוש בספריית הלקוח של Live Stream API מופיע במאמר ספריות הלקוח של Live Stream API. מידע נוסף מופיע במאמרי העזרה של Live Stream API Ruby API.

כדי לבצע אימות ב-Live Stream API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

require "google/cloud/video/live_stream"

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

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

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

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

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

מחיקת הקטגוריה של Cloud Storage

חשוב לדעת שכל הקבצים והתיקיות בדלי שנוצר על ידי Live Stream API נמחקים כשמפסיקים את הערוץ.

  1. פותחים את הדף Cloud Storage Browser במסוף Google Cloud .

    כניסה לדף Cloud Storage Browser

  2. מסמנים את התיבה ליד הקטגוריה שיצרתם.

  3. לוחצים על Delete.

  4. בחלון הקופץ שמופיע, לוחצים על מחיקה כדי למחוק סופית את הקטגוריה ואת התוכן שלה.

ביטול פרטי הכניסה

  1. אם תרצו, תוכלו לבטל את פרטי הכניסה שיצרתם ולמחוק את הקובץ המקומי של פרטי הכניסה.

    gcloud auth application-default revoke
  2. אם רוצים, מבטלים את פרטי הכניסה של ה-CLI של gcloud.

    gcloud auth revoke

המאמרים הבאים