Integre o ApsaraVideo Player SDK for Web à sua aplicação web e configure a reprodução básica de vídeo.
Observações 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 Baixe o ApsaraVideo Player SDK.
O ApsaraVideo Player SDK for Web V2.14.0+ oferece suporte à reprodução de vídeo H.265, e a versão V2.20.2+ suporta H.266. Este tópico aborda o H.264. Para H.265 e H.266, consulte Play H.265 and H.266 videos.
Preparativos
Obtenha o nome de domínio e a chave de licença do seu site. Gerencie a licença.
Acesso rápido com AI Skill
Se você usa ferramentas de programação com IA compatíveis com Agent Skills (como Qoder e Claude Code), instale o Skill oficial do player para que a IA gere o código de integração pronto para execução.
-
Instalação.
Método 1: Execute o comando no diretório raiz do projeto para instalação automática.
npx skills add https://player.alicdn.com/file/aliplayer-web-setup.tar.gzMétodo 2: Baixe manualmente o pacote compactado e coloque-o no diretório skills da ferramenta de programação com IA.
Copie o diretório aliplayer-web-setup para o diretório skills da ferramenta correspondente. Exemplo:
GLOBAL EFFECTIVE:~/.qoder/skills/aliplayer-web-setup/
Effective for current item only:<Project Root Directory>/.qoder/skills/aliplayer-web-setup/
Consulte a documentação oficial para verificar o caminho do diretório skills em outras ferramentas de programação com IA.
NotaApós concluir a instalação por qualquer um dos métodos, reinicie a ferramenta de programação com IA para ativar o Skill.
-
Uso.
Descreva o requisito em linguagem natural. Exemplo:Help me connect to Aliyun player in React project, play on-demand video, need private encryption.
A IA confirmará o framework front-end, o tipo de transmissão (sob demanda ou ao vivo), a necessidade de criptografia, o modo de origem do vídeo e outras informações. Em seguida, gerará o código completo de integração do player.
O código gerado usa a License de teste por padrão, restrita à depuração local. Para o lançamento oficial, substitua-a pela License oficial solicitada no console. Para mais detalhes, consulte Gerencie a licença.
Acesso rápido manual
Estas etapas integram o ApsaraVideo Player SDK for Web em um projeto web básico. Para React ou Vue, baixe o demo em Online trial and demo source code.
1. Importar o Web SDK
Importação via pacote NPM
-
Adicione a dependência
aliyun-aliplayerao seu projeto.npm install aliyun-aliplayer --save -
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';
Importação via tag script
Os caminhos dos arquivos JavaScript e CSS mudaram a partir da versão 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 <body> e um nó <div> 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
Reprodução baseada em URLs
Defina o parâmetro source como a URL de reprodução de um arquivo de mídia de um service 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 complexos de assinatura. Teste 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.");
}
);
Reprodução baseada em VID e PlayAuth
Defina vid como o ID da mídia e playauth como a credencial de reprodução.
Após carregar um arquivo de mídia, localize seu ID no console do ApsaraVideo VOD em Media Files > Audio/Video. Alternativamente, chame a operação SearchMedia.
Chame a operação GetVideoPlayAuth para obter a credencial de reprodução. Recomendamos integrar o ApsaraVideo VOD SDK para evitar cálculos complexos de assinatura. Teste a api no OpenAPI Explorer.
Recomendamos a reprodução baseada em VidAuth em vez de STS devido à 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.");
}
);
Reprodução baseada em VID e STS
A reprodução baseada em STS utiliza 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.");
}
);
Reprodução criptografada
O ApsaraVideo VOD oferece suporte à criptografia proprietária da Alibaba Cloud e à criptografia DRM. Play an encrypted video in a web browser.
Ao inicializar o player 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 expirará ou falhará. 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.
Para todas as opções de inicialização, consulte Parameters.
Reproduzir transmissões ao vivo
Transmissão ao vivo baseada em URL
Defina source como a URL de transmissão e isLive como true.
A URL de transmissão pode ser de um service 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.");
}
);
Transmissão ao vivo com criptografia DRM
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.
Gere uma URL RTS com o URL generator no console do ApsaraVideo Live.
O player integra o RTS SDK para reprodução RTS. A latest version é usada por padrão. Substitua-a com o parâmetro rtsVersion.
Se o RTS estiver indisponível, o player retornará para HLS ou HTTP-FLV. O FLV tem prioridade 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
Para propriedades, métodos e eventos do player, consulte Aliplayer API Reference.