Todos os produtos
Search
Central de documentação

ApsaraVideo VOD:Integrate ApsaraVideo Player SDK for Web

Última atualização: Oct 18, 2026

Integre o ApsaraVideo Player SDK for Web à sua aplicação web e configure a reprodução básica de vídeo.

Notas de uso

  • Este tópico usa o ApsaraVideo Player SDK for Web V2.25.1 como exemplo. Recomendamos a versão mais recente. Para baixá-la, consulte Download ApsaraVideo Player SDK.

  • O ApsaraVideo Player SDK for Web V2.14.0+ suporta reprodução de vídeo H.265, e a V2.20.2+ suporta H.266. Este tópico aborda H.264. Para H.265 e H.266, consulte Play H.265 and H.266 videos.

Preparativos

  • Você já obteve o nome de domínio e a chave de licença do seu site. Manage license.

Acesso rápido usando AI Skill

Se você usa ferramentas de programação com IA que suportam Agent Skills (como Qoder e Claude Code), instale o Skill oficial do player e a IA gera o código de integração pronto para execução.

  1. Instalação.

    Método 1: Execute o comando para instalar automaticamente no diretório raiz do projeto.

    npx skills add https://player.alicdn.com/file/aliplayer-web-setup.tar.gz

    Método 2: Baixe manualmente o pacote compactado e coloque-o no diretório de skills da ferramenta de programação com IA.

    Copie o diretório aliplayer-web-setup para o diretório de skills da ferramenta correspondente, por exemplo:

    • Efetivo globalmente: ~/.qoder/skills/aliplayer-web-setup/

    • Efetivo apenas para o projeto atual: <Project Root Directory>/.qoder/skills/aliplayer-web-setup/

    Consulte a documentação oficial para obter o caminho do diretório de skills de outras ferramentas de programação com IA.

    Nota

    Após a conclusão da instalação por qualquer um dos dois métodos, é necessário reiniciar a ferramenta de programação com IA para que o Skill entre em vigor.

  2. Uso.

    Descreva a necessidade em linguagem natural, por exemplo:Help me connect to Aliyun player in React project, play on-demand video, need private encryption.

    A IA primeiro confirmará o framework front-end, se é sob demanda ou ao vivo, se há criptografia, o modo de origem do vídeo e outras informações, e então gerará o código completo de integração do player.

Nota

O código gerado usa a License de teste por padrão e é limitado à depuração local. Para a publicação oficial, substitua pela License oficial solicitada no console. Para mais detalhes, consulte Manage license.

Acesso rápido manual

Estas etapas integram o ApsaraVideo Player SDK for Web em um projeto web básico. Para React ou Vue, baixe a demo em Online trial and demo source code.

1. Importar o Web SDK

Import by using NPM package

  1. Adicione a dependência aliyun-aliplayer ao seu projeto.

    npm install aliyun-aliplayer --save
  2. Importe o pacote de código e o arquivo de estilo no seu código.

    import Aliplayer from 'aliyun-aliplayer';
    import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css';

Import by using script tag

Nota

Os caminhos de armazenamento dos arquivos JavaScript e CSS foram alterados a partir da V2.16.3.

Original:

CSS: https://g.alicdn.com/de/prismplayer/version/skins/default/aliplayer-min.css

JS: https://g.alicdn.com/de/prismplayer/version/aliplayer-min.js

Novo:

CSS: https://g.alicdn.com/apsara-media-box/imp-web-player/version/skins/default/aliplayer-min.css

JS: https://g.alicdn.com/apsara-media-box/imp-web-player/version/aliplayer-min.js

<!--In this topic, Web SDK V2.25.1 is used as an example. If you want to use other versions, obtain the version number and replace 2.25.1 in the sample code.-->
<head>
  <link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.25.1/skins/default/aliplayer-min.css" />  // Required. You must add this CSS file.
  <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.25.1/aliplayer-min.js"></script>  // Required. You must add the .js file.
</head>

2. Fornecer um elemento de montagem

Adicione uma tag &lt;body&gt; e um nó &lt;div&gt; para montar a interface do player. Código de exemplo:

<body>
  <div id="J_prismPlayer"></div>
</body>

3. Inicializar o SDK

O SDK localiza o nó DOM com id="J_prismPlayer" e renderiza a interface do player.

var player = new Aliplayer({
  id: 'J_prismPlayer',
  license: {
    // Use the domain name and license key prepared
    domain: "example.com", // The domain name that you specified when you applied for a license
    key: "example-key" // The license key displayed in the ApsaraVideo VOD console after you have applied for a license
  }
});

Reproduzir um vídeo

Configure o player para diferentes cenários.

Reproduzir vídeos sob demanda

Playback based on URLs

Defina o parâmetro source como a URL de reprodução de um arquivo de mídia de um serviço de terceiros ou do ApsaraVideo VOD.

Chame a operação GetPlayInfo para obter a URL de reprodução de um arquivo de mídia no ApsaraVideo VOD. Recomendamos integrar o ApsaraVideo VOD SDK para evitar cálculos de assinatura complexos. Experimente a API no OpenAPI Explorer.

var player = new Aliplayer(
  {
    id: "J_prismPlayer",
    source: "<your play URL>", // The playback URL of a media file stored in a third-party VOD service or in ApsaraVideo VOD.
  },
  function (player) {
    console.log("The player is created.");
  }
);

Playback based on VID and PlayAuth

Defina vid como o ID da mídia e playauth como a credencial de reprodução.

  1. Após fazer upload de um arquivo de mídia, encontre o ID no console do ApsaraVideo VOD em Media Files > Audio/Video. Alternativamente, chame a operação SearchMedia.

  2. Chame a operação GetVideoPlayAuth para obter a credencial de reprodução. Recomendamos integrar o ApsaraVideo VOD SDK para evitar cálculos de assinatura complexos. Experimente a API no OpenAPI Explorer.

A reprodução baseada em VidAuth é recomendada em vez de STS pela simplicidade e segurança. Para comparação, consulte Credential method vs. STS method.

var player = new Aliplayer(
  {
    id: "J_prismPlayer",
    width: "100%",
    vid: "<your video ID>", // Required. The ID of the media file. Example: 1e067a2831b641db90d570b6480f****.
    playauth: "<your PlayAuth>", // Required. The playback credential.
    // authTimeout: 7200, // The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 7200 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
  },
  function (player) {
    console.log("The player is created.");
  }
);

Playback based on VID and STS

A reprodução baseada em STS usa um token STS temporário em vez de uma credencial de reprodução. Chame a operação AssumeRole para obter um token STS. Para mais informações, consulte Obtain an STS token.

var player = new Aliplayer(
  {
    id: "J_prismPlayer",
    width: "100%",
    vid: "<your video ID>", // Required. After you upload an audio or video file, you can log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video to view the ID of the audio or video file. Alternatively, you can call the SearchMedia operation provided by the ApsaraVideo VOD SDK to obtain the ID. Example: 1e067a2831b641db90d570b6480f****.
    accessKeyId: "<your AccessKey ID>", // Required. The AccessKey ID is returned when the temporary STS token is generated.
    securityToken: "<your STS token>", // Required. The STS token. To obtain an STS token, call the AssumeRole operation.
    accessKeySecret: "<your AccessKey Secret>", // Required. The AccessKey secret is returned when the temporary STS token is generated.
    region: "<region of your video>", // Required. The ID of the region in which the media asset resides, such as cn-shanghai, eu-central-1, or ap-southeast-1.
    // authTimeout: 7200, // The validity period of the playback URL. Unit: seconds. This setting overwrites the validity period that you configured in the ApsaraVideo VOD console. If you leave this parameter empty, the default value 7200 is used. The validity period must be longer than the actual duration of the video. Otherwise, the playback URL expires before the playback is complete.
  },
  function (player) {
    console.log("The player is created.");
  }
);

Encrypted playback

O ApsaraVideo VOD suporta criptografia proprietária da Alibaba Cloud e criptografia DRM. Play an encrypted video in a web browser.

Quando o player é inicializado no modo de reprodução VID, o Aliplayer SDK envia uma solicitação GetPlayInfo para vod.{region}.aliyuncs.com(vod-product.{region}aliyuncs.com) para obter o endereço de reprodução. Se a rede não conseguir acessar o nome de domínio (por exemplo, em um ambiente de intranet), a solicitação expira ou falha. Certifique-se de que vod.{region}.aliyuncs.com(vod-product.{region}aliyuncs.com) e o nome de domínio CDN estejam acessíveis pela rede.

Nota

Para todas as opções de inicialização, consulte Parameters.

Reproduzir transmissões ao vivo

URL-based live streaming

Defina source como a URL de transmissão e isLive como true.

A URL de transmissão pode ser de um serviço de terceiros ou do ApsaraVideo Live. Gere URLs com o URL generator no console do ApsaraVideo Live.

var player = new Aliplayer(
  {
    id: "J_prismPlayer",
    source: "<your play URL>", // The streaming URL can be a third-party streaming URL or a streaming URL that is generated in ApsaraVideo Live.
    isLive: true, // Specifies whether to play live streams.
  },
  function (player) {
    console.log("The player is created.");
  }
);

DRM-encrypted live streaming

Para transmissão ao vivo com criptografia DRM: Play an encrypted video.

Real-Time Streaming (RTS)

O RTS reproduz vídeos a partir de URLs sem parâmetros adicionais.

  1. Gere uma URL RTS com o URL generator no console do ApsaraVideo Live.

  2. O player integra o RTS SDK para reprodução RTS. A versão mais recente é usada por padrão. Substitua com o parâmetro rtsVersion.

  3. Se o RTS não estiver disponível, o player faz fallback para HLS ou HTTP-FLV. O FLV é priorizado quando suportado.

var player = new Aliplayer(
  {
    id: "J_prismPlayer",
    source: "<your play URL>", // The RTS playback URL. The artc:// protocol is used.
    isLive: true, // Specifies whether to play live streams.
    // rtsFallback: false, //Optional. Specifies whether to enable the RTS playback degradation feature. Default value: true.
    // rtsFallbackType: 'HLS', //Optional. The degraded protocol that you want to use. You can specify HLS or FLV. By default, this parameter is left empty. In this case, the default policy is used and the system tries to play the stream over FLV first. If your browser does not support FLV, the system plays the stream over HLS.
    // rtsFallbackSource: '<your play URL>', // Optional. The degraded protocol that you want to use.
    // rtsVersion: 'x.x.x', // Optional. The version of the RTS SDK.
  },
  function (player) {
    console.log("The player is created.");
  }
);
// The event that is triggered when a stream is pulled over RTS. Listen for this event to obtain the TraceId. In the event callback, traceId indicates the TraceId that is used for stream pulling and source indicates the playback URL of the RTS stream.
player.on("rtsTraceId", function (event) {
  console.log("EVENT rtsTraceId", event.paramData);
});
// The event that is triggered when a degraded protocol is used for playback. reason indicates the degradation cause and fallbackUrl indicates the alternative URL.
player.on("rtsFallback", function (event) {
  console.log(" EVENT rtsFallback", event.paramData);
});

Referência