Se o navegador não oferecer suporte a WebRTC ou se a extração de stream via Real-Time Streaming (RTS) falhar, utilize HTTP Live Streaming (HLS) ou HTTP Flash Video (HTTP-FLV) como alternativa de reprodução. Este tópico aborda os cenários de fallback e a implementação tanto para players personalizados integrados ao Web RTS SDK quanto para o ApsaraVideo Player.
Visão geral
A reprodução RTS pode recorrer a um protocolo degradado nas seguintes situações:
-
O navegador não oferece suporte a WebRTC ou H.264.
NotaO Web RTS SDK depende do suporte do navegador a WebRTC. Para consultar a lista de navegadores testados, veja Versões de navegadores suportadas. Use a função
isSupportdo Web RTS SDK para verificar a compatibilidade do navegador. Se o navegador oferecer suporte a WebRTC, mas não constar na lista, realize testes completos e ignore a verificaçãoisSupport. Falhas em requisições de sinalização causadas por URL de source inválida, configuração HTTPS incorreta ou configuração RTS inadequada.
Tempo limite excedido no início da reprodução ou interrupção do stream durante a execução.
As seções a seguir descrevem como implementar o fallback de protocolo para um player personalizado integrado ao Web RTS SDK e para o ApsaraVideo Player.
Use seu próprio player integrado ao Web RTS SDK
Use o Web RTS SDK V2.5.1 ou superior. Para mais detalhes, consulte Notas de versão.
O código de exemplo abaixo é simplificado. Baixe o código de exemplo completo para reprodução com protocolo degradado para acessar a implementação completa.
/**
* Scenarios in which you can use a degraded protocol:
* 1. The browser is not supported. Configure isSupport().catch to use a degraded protocol.
* 2. A reconnection failure occurs when connection is being established or during playback. In this case, the 10410 error code is returned in the onError event.
**/
var pullStreamUrl = 'The RTS source URL.';
var fallbackUrl = 'The URL based on a degraded protocol, such as HLS.';
// Initialize the SDK.
var aliRts = AliRTS.createClient();
aliRts.on('onError', (error) => {
console.log(error.errorCode, error.message); // The error code and error message.
// Determine whether to use a degraded protocol.
switch(error.errorCode){
case 10410: // Reconnection for stream pulling (subscription) failed.
fallback(); // Use a degraded protocol.
break;
default:
}
});
// Check whether the browser is supported.
// You can skip the isSupport check and directly execute subscribeRts to pull the steam if the browser is not in the list that is described in the following topic: ApsaraVideo Live > User Guide > Real-Time Streaming > Web RTS SDK > Web RTS SDK for stream pulling > Integrate Web RTS SDK with other players > SDK overview. This operation may cause risks. Perform a full test before you perform this operation.
aliRts.isSupport({ isReceiveVideo: true }).then(subscribeRts).catch(fallback)
function subscribeRts() {
aliRts.subscribe(pullStreamUrl, {
// mediaTimeout: 6000 // Specify the timeout period.
// retryTimes: 5, // Specify the number of reconnection attempts. Default value: 5.
// retryInterval: 2000,// Specify the interval between reconnection attempts. Default value: 2000. Unit: milliseconds.
}).then((remoteStream) => {
remoteStream.play(mediaElement);
}).catch(() => {})
}
// Use a degraded protocol for playback.
function fallback() {
// The following code provides an example. You can choose an appropriate player based on the protocol that you use.
hlsPlayer.play(fallbackUrl)
}
Use o ApsaraVideo Player
O ApsaraVideo Player possui integração nativa com o Web RTS SDK e oferece suporte a fallback automático de protocolo. Basta fornecer uma URL de fallback para ativar esse recurso.
Use o ApsaraVideo Player V2.9.23 ou superior. Para mais informações, veja Notas de versão do ApsaraVideo Player SDK for Web.
Este código de exemplo é uma versão simplificada. Baixe o código de exemplo completo para reprodução com protocolo degradado no ApsaraVideo Player para obter a implementação integral.
/**
* By default, ApsaraVideo Player plays the RTS stream from the source URL. If the playback fails, ApsaraVideo Player automatically plays the stream from the URL provided by rtsFallbackSource, such as an HLS URL.
* Scenarios in which a degraded protocol may be used:
* 1. The browser does not support RTS. ApsaraVideo Player uses a degraded protocol to play the stream.
* 2. Signaling requests fail due to an invalid source URL, invalid HTTPS configuration, or invalid RTS configuration. ApsaraVideo Player uses a degraded protocol to play the stream.
* 3. Playback startup times out or the stream is interrupted during playback. ApsaraVideo Player retries playback based on the custom policy. If the retry fails, ApsaraVideo Player uses a degraded protocol to play the stream.
**/
var options = {
"id": "player-con",
"source": "The RTS playback URL.",
"rtsFallbackSource": "The URL based on a degraded protocol, such as HLS.",
"width": "100%",
"height": "500px",
"autoplay": true,
"isLive": true,
"playsinline": true,
"skipRtsSupportCheck": false, // You can set the value to true to skip the check and forcibly use RTS if the browser is not in the list that is described in the following topic: ApsaraVideo Live > User Guide > Real-Time Streaming > Web RTS SDK > Web RTS SDK for stream pulling > Integrate Web RTS SDK with other players > SDK overview. This operation may cause risks. Perform a full test before you perform this operation.
/**
* If RTS stream pulling times out, a retry occurs by default.
* The following parameters are used to control the retry policy before a degraded protocol is used. For example, if the stream cannot be pulled after 3,000 milliseconds, a retry occurs. If the stream still cannot be pulled after another 3,000 milliseconds, a degraded protocol is used. The total waiting period is 6,000 milliseconds.
**/
// The period of time after which a retry occurs if the RTS stream fails to be pulled. Default value: 3000. Unit: milliseconds.
// rtsLoadDataTimeout: 2000,
// The number of retries for failed RTS stream pulling. Default value: 5. We recommend that you set this parameter to 1. This way, the total waiting period can be reduced.
liveRetry: 1,
};
var player = new Aliplayer(options, function () {/* player ready */});
// The event that is triggered when a degraded protocol is used.
player.on('rtsFallback', function(event) {
// event.paramData.reason The reason for degradation.
// event.paramData.fallbackUrl The URL based on a degraded protocol.
})
É possível usar o Web RTS SDK em mini programas do WeChat?
O Web RTS SDK não executa em mini programas nativos do WeChat, pois eles não oferecem suporte ao protocolo de sinalização RTS. Como solução alternativa, incorpore páginas web integradas ao SDK no WebView dos mini programas do WeChat.