Integrate the Live Producer Web SDK

更新时间:
复制 MD 格式

This topic describes how to integrate the Live Producer Web SDK and use the diagnostic tool.

Note
  • Versions earlier than V2.3.0 may cause exceptions. We recommend upgrading to V2.3.0. For upgrade instructions, see Upgrade from V2.2.X to V2.3.0.

  • After upgrading to V2.3.0, follow the integration method in this topic to use the latest Web SDK version.

Prerequisites

  • You are familiar with the features and use cases of Live Producer, and how to call its APIs. For more information, see Console guide and Use a CommonRequest.

  • You have activated the Web SDK license. For more information, see Activate a license.

  • You have activated the services required for Live Producer and added an accelerated domain name. For more information, see Activate Live Producer and Add an accelerated domain name.

  • (Optional) For recording, you have granted ApsaraVideo Live permission to write to Object Storage Service (OSS). For more information, see Store recordings in OSS.

  • (Optional) For local ingest, you have associated the current streaming domain name with an ingest domain name. For more information, see Associate a streaming domain name and an ingest domain name.

  • (Optional) For local ingest, you have enabled Real-Time Streaming (RTS) for the ingest domain name that is associated with the streaming domain name. For more information, see Quick start for ultra-low-latency live streaming.

  • The Live Producer Web SDK is compatible with the following browser versions.

    Browser

    Minimum version

    Google Chrome

    60

    Firefox

    25

    Microsoft Edge

    12

    Safari

    10

    Opera

    36

    QQ Browser

    10

    360 Browser

    stable

    Sogou Browser

    stable

    UC Browser

    stable

    LieBao Browser

    stable

Integrate the Live Producer Web SDK

  1. Add the integration code.

    Add the following script and stylesheet references to your page to include the latest Live Producer Web SDK code.

    Important

    When you reference the code below, replace @@version@@ with the latest version number of the Web SDK. The format is a.b.c. For example: 2.3.4. For the latest version number, see Web SDK Release History.

    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8" />
      <title>Your App</title>
      <!-- Live Producer style file -->
      <link rel="stylesheet" href="https://g.alicdn.com/cdn-fe/caster-next/@@version@@/index.css" />
      <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.9.19/skins/default/aliplayer-min.css">
    </head>
    <body>
      <!-- The element where Live Producer will be mounted -->
      <div id="caster-root"></div>
      <!-- Player script -->
      <script src="https://g.alicdn.com/de/prismplayer/2.9.19/aliplayer-min.js"></script>
      <!-- Live Producer SDK script -->
      <script src="https://g.alicdn.com/cdn-fe/caster-next/@@version@@/index.js"></script>
    </body>
    </html>
  2. Initialize the SDK.

    • Pass the business identifier, the host element ID, the Live Producer ID, and an optional language setting.

    • Register all services. For more information, see Service (API) registration.

    const { default: Caster } = window.AliCaster;
    // After the Live Producer SDK is loaded, the AliCaster object is mounted globally.
    const services = {};
    const caster = new Caster(
      {
        /**
         * type: string
         * A unique identifier for your business.
         * You can obtain this identifier when you apply for a license by email.
         */
        BizCode: 'BizCode',
        /**
         * type: string
         * The ID of the element where Live Producer will be mounted. Make sure this element exists.
         */
        Container: 'caster-root',
        /**
         * type: string
         * The region where your API service is deployed.
         * China (Shanghai): cn-shanghai
         * China (Beijing): cn-beijing
         */
        Region: 'cn-shanghai',
        /**
         * type: string
         * The Live Producer ID (`CasterId`), returned by the `CreateCaster` API. If you create an instance in the ApsaraVideo Live console, the instance name in the Live Producer list is the ID.
         */
        Id: 'LIVEPRODUCER_POST-cn-0pp0gal****',
        /**
         * type: boolean
         * Must be set to true.
         */
        UseRts: true,
        /**
         * type: 'zh' | 'en'
         * Optional. Supported languages: 'zh' (Simplified Chinese) and 'en' (US English). Default: 'zh'.
         */
        // Language: 'en',
        /**
         * type: string
         * The ID of the resource group that contains the Live Producer instance. This ID is returned by the `DescribeCasters` API. If you omit this parameter, this information does not appear in Live Producer.
         */
        // ResourceGroupId: "rg-xxxxxxxxxx", // This is an example.
        /**
         * type: boolean
         * Specifies whether to enable the diagnostic tool. Note: Do not use the Debug parameter in a production environment. For more information, see Diagnostic tool.
         */
        // Debug: true
      },
      /**
       * type: object
       * All services to be registered. For a code sample, see Service (API) registration.
       */
      services
    );
    // When you are finished with Live Producer, call the destroy method to clean up side effects such as timers.
    caster.destroy();

Service (API) registration

The Live Producer Web SDK handles only the UI and user interactions, not the request logic. You must encapsulate each API as a JavaScript function and pass it to the SDK during initialization. The SDK then calls these functions to make requests. These functions must send requests to your server, which then forwards them to the Alibaba Cloud server-side.

Front-end perspective

The following sample shows how to register request functions when you initialize the SDK:

const services = {
  // You can replace fetch with any request library. Make sure to pass through the parameters.
  DescribeCasters: (params) => fetch('/DescribeCasters', params),
  // other services...
};
const caster = new Caster({/** configs **/}, services);

The example above registers the DescribeCasters function. This function initiates a /DescribeCasters request, passes through the parameters, and returns a Promise for this request. In this process, the /DescribeCasters request is sent to your server-side API, which then calls the Alibaba Cloud OpenAPI.

List of APIs to register

export interface ServicesImp {
  // Product: Live Producer, API documentation https://help.aliyun.com/document_detail/60293.html
  DescribeCasters: (...args: any[]) => Promise<Resp>;
  DescribeCasterConfig: (...args: any[]) => Promise<Resp>;
  StopCaster: (...args: any[]) => Promise<Resp>;
  StartCaster: (...args: any[]) => Promise<Resp>;
  DescribeCasterVideoResources: (...args: any[]) => Promise<Resp>;
  AddCasterVideoResource: (...args: any[]) => Promise<Resp>;
  DeleteCasterVideoResource: (...args: any[]) => Promise<Resp>;
  DescribeCasterChannels: (...args: any[]) => Promise<Resp>;
  DescribeCasterScenes: (...args: any[]) => Promise<Resp>;
  StartCasterScene: (...args: any[]) => Promise<Resp>;
  StopCasterScene: (...args: any[]) => Promise<Resp>;
  UpdateCasterSceneConfig: (...args: any[]) => Promise<Resp>;
  DescribeCasterLayouts: (...args: any[]) => Promise<Resp>;
  DescribeCasterComponents: (...args: any[]) => Promise<Resp>;
  DeleteCasterComponent: (...args: any[]) => Promise<Resp>;
  EffectCasterUrgent: (...args: any[]) => Promise<Resp>;
  DeleteCasterSceneConfig: (...args: any[]) => Promise<Resp>;
  DescribeCasterSceneAudio: (...args: any[]) => Promise<Resp>;
  DeleteCasterLayout: (...args: any[]) => Promise<Resp>;
  SetCasterConfig: (...args: any[]) => Promise<Resp>;
  ModifyCasterVideoResource: (...args: any[]) => Promise<Resp>;
  SetCasterChannel: (...args: any[]) => Promise<Resp>;
  ModifyCasterLayout: (...args: any[]) => Promise<Resp>;
  AddCasterLayout: (...args: any[]) => Promise<Resp>;
  CopyCasterSceneConfig: (...args: any[]) => Promise<Resp>;
  UpdateCasterSceneAudio: (...args: any[]) => Promise<Resp>;
  DescribeCasterStreamUrl: (...args: any[]) => Promise<Resp>;
  AddCasterComponent: (...args: any[]) => Promise<Resp>;
  ModifyCasterComponent: (...args: any[]) => Promise<Resp>;
  DescribeLiveDomainMapping: (...args: any[]) => Promise<Resp>;
  RealTimeRecordCommand: (...args: any[]) => Promise<Resp>;
  // APIs for virtual studio type Live Producer instances
  ModifyStudioLayout: (...args: any[]) => Promise<Resp>;
  AddStudioLayout: (...args: any[]) => Promise<Resp>;
  DescribeStudioLayouts: (...args: any[]) => Promise<Resp>;
  DeleteStudioLayout: (...args: any[]) => Promise<Resp>;
  DescribeStudioDefaultBgImageList: (...args: any[]) => Promise<Resp>;
  CasterSnapshotReferScene: (...args: any[]) => Promise<Resp>;
  DescribeCasterRoomUsers: (...args: any[]) => Promise<Resp>;
  // APIs for show list type Live Producer instances
  DescribeShowList: <R = any, T = any>(payload: R) => Promise<Resp<T>>;
  AddShowIntoShowList: <R = any, T = any>(payload: R) => Promise<Resp<T>>;
  RemoveShowFromShowList: (...args: any[]) => Promise<Resp>;
  ModifyShowList: (...args: any[]) => Promise<Resp>;
  PlayChoosenShow: (...args: any[]) => Promise<Resp>;
  // Product: ApsaraVideo Live, API documentation https://help.aliyun.com/document_detail/48207.html
  DescribeLiveStreamsOnlineList: (...args: any[]) => Promise<Resp>;
  DescribeLiveDomainConfigs: (...args: any[]) => Promise<Resp>;
  DescribeLiveUserDomains: (...args: any[]) => Promise<Resp>;
  // Product: ApsaraVideo VOD, API documentation https://help.aliyun.com/document_detail/60574.html
  GetPlayInfo: (...args: any[]) => Promise<Resp>;
  CreateUploadImage: (...args: any[]) => Promise<Resp>;
  SearchMedia: (...args: any[]) => Promise<Resp>;
  GetImageInfo: <T = any>(...args: any[]) => Promise<Resp<T>>;
  GetVideoInfos: (...args: any[]) => Promise<Resp>;
  // Product: Object Storage Service (OSS), API documentation https://help.aliyun.com/document_detail/31948.html
  GetService: (...args: any[]) => Promise<Resp>;
  GetBucket: (...args: any[]) => Promise<Resp>;
  // Product: Resource Access Management (RAM), API documentation https://help.aliyun.com/document_detail/62184.html
  ListPoliciesForRole: (...args: any[]) => Promise<Resp>;
}
export interface Resp<T = any> {
  code: string;
  httpStatusCode: string;
  requestId: string;
  successResponse: boolean;
  data: T;  // Business data
}

Handle service return values

Each service must return a Promise. Whether the request succeeds or fails, always call resolve to return a result.

The returned data must follow the structure below, where data contains the specific business data.

interface Resp<T = any> {
  code: string;
  httpStatusCode: string;
  requestId: string;
  successResponse: boolean;
  data: T;
}
  • A successful OpenAPI request returns data similar to the following:

    {
      "RequestId": "996B6B22-FF2C-4069-929A-5B63261410C2",
      "Total": 0,
      "CasterList": {
        "Caster": []
      }
    }

    Place the returned data in the data field and use the resolve method to return the complete response to the SDK, as shown below.

    {
      "code": "200",
      "httpStatusCode": "200",
      "requestId": "996B6B22-FF2C-4069-929A-5B63261410C2",
      "successResponse": true,
      "data": {
        "RequestId": "996B6B22-FF2C-4069-929A-5B63261410C2",
        "Total": 0,
        "CasterList": {
          "Caster": []
        }
      }
    }
  • A failed OpenAPI request returns data similar to the following:

    {
      "RequestId": "F7FA5276-75D0-4C03-AC04-C5E35AB95CF4",
      "HostId": "example.aliyundoc.com",
      "Code": "InvalidCaster.NotFound",
      "Message": "The CasterId provided does not exist in our records.",
      "Recommend": "https://error-example.aliyundoc.com/status/search?Keyword=InvalidCaster.NotFound&source=PopGw"
    }

    In this case, use the resolve method to return the following data to the SDK.

    {
      "code": "InvalidCaster.NotFound",
      "requestId": "F7FA5276-75D0-4C03-AC04-C5E35AB95CF4"
    }

Exceptions to ignore

Typically, if the status code of a response is not 200, you must handle it as an exception. However, the following error codes can be ignored.

API

Error code

DescribeCasterStreamUrl

'InvalidScene.NotFound', 'InvalidDomainName.NotFound'

DescribeCasterScenes

'InvalidDomainName.NotFound'

UpdateCasterSceneConfig

'MissingLayoutId'

Server-side perspective

The following example shows how to send a DescribeLiveUserDomains request:

// This file is auto-generated, don't edit it. Thanks.
package demo;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.live20161101.models.*;
import com.aliyun.sdk.service.live20161101.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;
//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.io.*;
public class DescribeLiveUserDomains {
    public static void main(String[] args) throws Exception {
        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Sets the connection timeout. The default is 10 seconds.
                .responseTimeout(Duration.ofSeconds(10)) // Sets the response timeout. The default is 20 seconds.
                .maxConnections(128) // Sets the connection pool size.
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Sets the connection pool timeout. The default is 30 seconds.
                // Configure the proxy.
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // For HTTPS connections, you must configure the certificate or ignore it by using .ignoreSSL(true).
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/
        // Configure credentials.
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // Use an STS token.
                .build());
        // Configure the client.
        AsyncClient client = AsyncClient.builder()
                .region("<Your Region ID>") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient. Otherwise, the default Apache HttpClient is used.
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration. You can set the endpoint, HTTP request parameters, and so on.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                  // For the endpoint, see https://api.aliyun.com/product/live
                                .setEndpointOverride("live.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Set the parameters for the API request.
        DescribeLiveUserDomainsRequest describeLiveUserDomainsRequest = DescribeLiveUserDomainsRequest.builder()
                .liveDomainType("<Your LiveDomainType>")
                .domainName("<Your DomainName>")
                .regionName("<Your RegionName>")
                .domainSearchType("<Your DomainSearchType>")
                // Request-level configuration. You can set HTTP request parameters and so on.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Get the API response asynchronously.
        CompletableFuture<DescribeLiveUserDomainsResponse> response = client.describeLiveUserDomains(describeLiveUserDomainsRequest);
        // Get the API response synchronously.
        DescribeLiveUserDomainsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Process the response asynchronously.
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handle exceptions.
            System.out.println(throwable.getMessage());
            return null;
        });*/
        // Close the client.
        client.close();
    }
}

Diagnostic tool

To help developers troubleshoot issues during integration, the Live Producer Web SDK provides a diagnostic tool. This tool can automatically check parameters, environment settings, and service registrations before initialization.

Note
  • The diagnostic tool is supported only in Web SDK V2.2.10 and later.

  • Do not use the Debug parameter in a production environment.

Usage

  1. You can enable the diagnostic tool by adding the parameter Debug:true when you initialize the SDK. The following is a code example:

    new Caster({
      BizCode: 'xxx',
      Container: 'xxx',
      Id: 'xxx',
      Region: 'xxx',
      Language: 'xxx',
      // Enable the diagnostic tool
      Debug: true
    }, service);
  2. Open your browser's console and refresh the page. The console displays the diagnostic information. For example, if a service registration check fails, the log indicates that no service was registered and provides a reference link:

    
    [Diagnostic Info] ────────── Diagnostics started. Check the console output. ──────────
    [Diagnostic Info] [Initialization Parameters] Starting check...
    [Diagnostic Info] [Initialization Parameters] BizCode=xxx
    [Diagnostic Info] [Initialization Parameters] Id=xxx
    [Diagnostic Info] [Initialization Parameters] Region=cn-shanghai
    [Diagnostic Info] [Initialization Parameters] Container=caster-root
    [Diagnostic Info] [Initialization Parameters] Check complete.
    [Diagnostic Info] [WebRTC Environment] Starting check...
    [Diagnostic Info] [WebRTC Environment] hostname=localhost protocol=http:
    [Diagnostic Info] [WebRTC Environment] Check complete.
    [Diagnostic Info] [Service Registration] Starting check...
    [Diagnostic Info] [Service Registration] Registered services: undefined
    [Diagnostic Info] [Service Registration] No registered service found.
    * See the "Service (API) registration" section in https://help.aliyun.com/document_detail/214219.html

FAQ

See FAQ about Web SDK integration.