Lista as classes, métodos e eventos do SDK de co-streaming Web do ApsaraVideo Live para ingestão e recebimento de streams.
Classes básicas
|
Classe |
Descrição |
||||||
|
AlivcLivePusher |
Classe de ingestão de stream. Nota
Acesse via window.AlivcLivePush.AlivcLivePusher. |
||||||
|
AlivcLivePlayer |
Classe de recebimento de stream. Nota
Acesse via window.AlivcLivePush.AlivcLivePlayer. |
||||||
AlivcLivePusher (ingestão de stream)
Lista de métodos
|
Método |
Descrição |
||||||
|
Consulta câmeras. Método estático. |
|||||||
|
Consulta microfones. Método estático. |
|||||||
|
Consulta dispositivos de reprodução. Método estático. |
|||||||
|
Verifica os requisitos do WebRTC. Método estático. |
|||||||
|
Verifica o suporte ao compartilhamento de tela. Método estático. |
|||||||
|
Inicializa os parâmetros de ingestão de stream. |
|||||||
|
Libera a instância de ingestão de stream. |
|||||||
|
Inicia a pré-visualização. |
|||||||
|
Para a pré-visualização. |
|||||||
|
Inicia a ingestão de stream. |
|||||||
|
Reinicia a ingestão de stream. |
|||||||
|
Reconecta e continua a ingestão de stream. |
|||||||
|
Para a ingestão de stream. |
|||||||
|
Liga o microfone ou alterna para outro microfone. |
|||||||
|
Desliga o microfone. |
|||||||
|
Consulta o ID do dispositivo do microfone. |
|||||||
|
Liga a câmera ou alterna para outra câmera. |
|||||||
|
Desliga a câmera. |
|||||||
|
Consulta o ID do dispositivo da câmera. |
|||||||
|
Inicia o compartilhamento de tela. |
|||||||
|
Para o compartilhamento de tela. |
|||||||
|
Inicia a ingestão do stream secundário personalizado. |
|||||||
|
Para a ingestão do stream secundário personalizado. |
|||||||
|
Silencia ou reativa o áudio do stream. (A ingestão de stream não é interrompida.) |
|||||||
|
Exibe ou oculta o vídeo do stream. (A ingestão de stream não é interrompida.) |
|||||||
|
Consulta as últimas estatísticas de ingestão de stream relatadas. |
|||||||
|
Consulta a URL de ingestão. |
|||||||
|
Consulta o ID do canal. |
|||||||
|
Consulta o ID do usuário. |
|||||||
|
Atualize o layout para retransmissão e mixagem de streams. |
|||||||
|
Consulta a resolução. |
|||||||
|
Atualize a resolução. |
|||||||
|
Consulta a taxa de quadros. |
|||||||
|
Atualize a taxa de quadros. |
|||||||
|
Consulta as informações de MediaStream do stream atual. |
|||||||
|
Consulta o ID de rastreamento. |
|||||||
|
Defina a largura, altura, taxa de bits e taxa de quadros da faixa de tela. |
|||||||
Detalhes
-
getCameras: consulta câmeras. Método estático.
/** * Query cameras. * @return {Promise<MediaDeviceInfo[]>} */ const cameras = await AlivcLivePusher.getCameras(); -
getMicrophones: consulta microfones. Método estático.
/** * Query microphones. * @return {Promise<MediaDeviceInfo[]>} */ const microphones = await AlivcLivePusher.getMicrophones(); -
getPlayoutDevices: consulta dispositivos de reprodução. Método estático.
/** * Query playback devices. * @return {Promise<MediaDeviceInfo[]>} */ const playoutDevices = await AlivcLivePusher.getPlayoutDevices(); -
checkSystemRequirements: verifica os requisitos do WebRTC. Método estático.
/** * Check whether the requirements for WebRTC are met. * @param {('sendonly' | 'recvonly' | 'sendrecv')} [direction] * @return {Promise<CheckResult>} */ const checkResult = await AlivcLivePusher.checkSystemRequirements(); // checkResult.support: boolean; Indicates whether the requirements are met. // checkResult.detail.isBrowserSupported: boolean; Indicates whether the browser is supported. // checkResult.detail.isH264DecodeSupported: boolean; Indicates whether H.264 decoding is supported. // checkResult.detail.isH264EncodeSupported: boolean; Indicates whether H.264 encoding is supported. // checkResult.detail.isWebRTCSupported: boolean; Indicates whether WebRTC is supported. -
checkScreenShareSupported: verifica o suporte ao compartilhamento de tela. Método estático.
/** * Check whether screen sharing is supported. * @returns {boolean} */ const isScreenShareSupported = AlivcLivePusher.checkScreenShareSupported(); -
init: inicializa os parâmetros de ingestão de stream.
/** * Initialize the RTC engine. * @param config Configure parameters. All the parameters are optional. * config.resolution: AlivcResolutionEnum; The resolution. * config.fps: AlivcFpsEnum; The frame rate. Unit: frames per second (FPS). * config.logLevel: LogLevel; The log level. Default value: ERROR. * config.connectRetryCount: number; The maximum number of reconnection attempts. * config.audio: boolean; Specifies whether to enable audio. * config.audioId: string; The ID of the default audio device. * config.video: boolean; Specifies whether to turn on the camera. * config.cameraId: string; The device ID of the default camera. * config.screen: boolean; Specifies whether to enable screen sharing. */ const pusher = new AlivcLivePush.AlivcLivePusher(); pusher.init({ resolution: AlivcLivePush.AlivcResolutionEnum.RESOLUTION_720P }); -
destroy: libera a instância de ingestão de stream.
// Release the stream ingest instance. You cannot use the instance after you release it. pusher.destroy() -
startPreview: inicia a pré-visualização.
/** * Start video preview. * @param {string | HTMLVideoElement} elementOrId The node where the video resides or the ID of the video. * @param {boolean} secondary Specifies whether to preview the secondary stream. This parameter is optional. By default, only the primary stream is previewed. * @return {Promise<MediaStream>} */ const stream = pusher.startPreview(elementOrId); -
stopPreview: para a pré-visualização.
/** * Stop video preview. * @param {string | HTMLVideoElement} elementOrId The node where the video resides or the ID of the video. This parameter is optional. If you do not specify this parameter, previewing for all videos is stopped. */ pusher.stopPreview(elementOrId); -
startPush: inicia a ingestão de stream.
/** * Start stream ingest. * @param {string} url The ingest URL. Example: artc://live.aliyun.com/push/.... * @return {Promise} */ await pusher.startPush(url);ImportanteEspecifique uma URL de ingestão usada para co-streaming. Para obter informações sobre como gerar URLs para co-streaming, consulte Gerador de URL de co-streaming.
-
restartPush: usa a URL de ingestão atual para reiniciar a ingestão de stream.
/** * Use the current ingest URL to restart stream ingest. * @return {Promise} */ await pusher.restartPush(); -
reconnectPush: reconecta e continua a ingestão de stream.
/** * Reconnect and continue stream ingest. * @param {string} url The new ingest URL. Example: artc://live.aliyun.com/push/.... * @return {Promise} */ await pusher.reconnectPush(url); -
stopPush: para a ingestão de stream.
/** * Stop stream ingest. * @return {Promise} */ await pusher.stopPush(url); -
startMicrophone: liga o microfone ou alterna para outro microfone.
/** * Turn on the microphone or switch to another microphone. * @param {string} deviceId The device ID of the microphone. This parameter is optional. * @return {Promise} */ await pusher.startMicrophone(deviceId); -
stopMicrophone: desliga o microfone.
/** * Turn off the microphone. * @return {Promise} */ await pusher.stopMicrophone(); -
getCurrentMicDeviceId: consulta o ID do dispositivo do microfone.
/** * Query the device ID of the microphone. * @return {string | undefined} The device ID of the microphone. */ const micId = pusher.getCurrentMicDeviceId(); -
startCamera: liga a câmera ou alterna para outra câmera.
/** * Turn on the camera or switch to another camera. * @param {string} deviceId The device ID of the camera. This parameter is optional. * @return {Promise} */ await pusher.startCamera(deviceId); -
stopCamera: desliga a câmera.
/** * Turn off the camera. * @return {Promise} */ await pusher.stopCamera(); -
getCurrentCameraDeviceId: consulta o ID do dispositivo da câmera.
/** * Query the device ID of the camera. * @return {string | undefined} The device ID of the camera. */ const cameraId = pusher.getCurrentCameraDeviceId(); -
startScreenShare: inicia o compartilhamento de tela.
/** * Start screen sharing. * @return {Promise} */ await pusher.startScreenShare(); -
stopScreenShare: para o compartilhamento de tela.
/** * Stop screen sharing. * @return {Promise} */ await pusher.stopScreenShare(); -
startCustomStream: inicia a ingestão do stream secundário personalizado.
/** * Start ingest of the custom secondary stream. * @param mediaStream The custom secondary stream. * @return {Promise<MediaStream>} */ await pusher.startCustomStream(mediaStream); -
stopCustomStream: para a ingestão do stream secundário personalizado.
/** * Stop ingest of the custom secondary stream. * @return {Promise<void>} */ await pusher.stopCustomStream(); -
mute: silencia ou reativa o áudio do stream. (A ingestão de stream não é interrompida.)
/** * Mute or unmute the stream. * @param {boolean} Specifies whether to mute the stream. * @returns {AlivcLivePusher} Returns the pusher instance for method chaining. */ pusher.mute(true); -
muteVideo: exibe ou oculta o vídeo do stream. (A ingestão de stream não é interrompida.)
/** * Display or stop displaying the stream. * @param mute Specifies whether to stop sending video data. Valid values: true and false. * @returns {AlivcLivePusher} Returns the pusher instance for method chaining. */ pusher.muteVideo(true); -
getLivePushStatsInfo: consulta as últimas estatísticas de ingestão de stream relatadas.
/** * Query the stream ingest statistics that was last reported. * @return {StatsInfo} The stream ingest statistics. */ const statsInfo = pusher.getLivePushStatsInfo(); -
getPushUrl: consulta a URL de ingestão.
/** * Query the ingest URL. * @return {string | undefined} The current ingest URL. */ const url = pusher.getPushUrl(); -
getChannelId: consulta o ID do canal.
/** * Query the channel ID. * @return {string | undefined} The current channel ID. */ const channelId = pusher.getChannelId(); -
getUserId: consulta o ID do usuário.
/** * Query the user ID. * @return {string | undefined} The current user ID. */ const userId = pusher.getUserId(); -
setLiveMixTranscodingConfig: atualize o layout para retransmissão e mixagem de streams.
/** * Update the layout for stream relay and mixing. * @param {AlivcLiveTranscodingConfig} config This parameter is optional. If you do not specify this parameter, stream relay and mixing are stopped. For more information, check the details about the AlivcLiveTranscodingConfig class. * @return {Promise} The result of the operation. */ const response = await pusher.setLiveMixTranscodingConfig(config); -
getResolution: consulta a resolução.
/** * Query the resolution. * @return {AlivcResolutionEnum | undefined} The resolution. */ const resolution = pusher.getResolution(); -
changeResolution: atualize a resolução.
/** * Update the resolution. * @param resolutionEnum The resolution that you want to use. If you set this parameter to Custom, specify a custom resolution. * @param width The width, which is required when you specify a custom resolution. * @param height The height, which is required when you specify a custom resolution. * @param bitrate The maximum bitrate. * @return {Promise} */ await pusher.changeResolution(AlivcResolutionEnum.RESOLUTION_720P); -
getFps: consulta a taxa de quadros.
/** * Query the frame rate. * @return {AlivcFpsEnum | undefined} The current frame rate. */ const fps = pusher.getFps(); -
changeFps: atualize a taxa de quadros.
/** * Update the frame rate. * @param {AlivcFpsEnum} fps The frame rate that you want to use. * @return {Promise} */ await pusher.changeFps(AlivcFpsEnum.FPS_30); -
getPublishMediaStream: consulta as informações de MediaStream do stream atual.
/** * Query the MediaStream information of the current stream. * @return {MediaStream | undefined} The MediaStream information of the stream. */ const mediaStream = pusher.getPublishMediaStream(); -
getLiveTraceId: consulta o ID de rastreamento.
/** * Query the trace ID. * @return {string} TraceId */ pusher.getLiveTraceId(); -
updateScreenVideoProfile: defina a largura, altura, taxa de bits e taxa de quadros da faixa de tela.
/** * Configure the width, height, bitrate, and frame rate of the screen track. (Due to browser constraints, the specified width and height are not applied.) * @param width * @param height * @param rate * @param fps * @return {Promise} */ await pusher.updateScreenVideoProfile(width,height,rate,fps);
AlivcLiveTranscodingConfig
Lista de parâmetros
|
Parâmetro |
Descrição |
||||||
|
width |
Largura do stream retransmitido. |
||||||
|
height |
Altura do stream retransmitido. |
||||||
|
backgroundColor |
Cor de fundo em hexadecimal. Exemplo: 0x000000. |
||||||
|
cropMode |
AlivcLiveTranscodingCropModeEnum
|
||||||
|
mixStreams |
AlivcLiveMixStream[]: Configuração de layout para cada stream na mixagem. |
||||||
AlivcLiveMixStream
Lista de parâmetros
|
Parâmetro |
Descrição |
||||||
|
userId |
ID do usuário participante da mixagem de streams. |
||||||
|
x |
Deslocamento no eixo X em pixels para o stream mixado. |
||||||
|
y |
Deslocamento no eixo Y em pixels para o stream mixado. |
||||||
|
width |
Largura do stream mixado. |
||||||
|
height |
Altura do stream mixado. |
||||||
|
zOrder |
Ordem das camadas. Valores maiores aparecem no topo. |
||||||
|
sourceType |
Tipo de source de vídeo. Valores válidos:
Valor padrão: 0. |
||||||
AlivcLivePusher.info
|
Evento |
Descrição |
||||||
|
bye |
Um espectador saiu da sala, seja por ter sido substituído por outros espectadores ou removido pelo streamer. |
||||||
|
pushstatistics |
Estatísticas do stream de ingestão. Disparado a cada 2 segundos. |
||||||
Código de exemplo:
pusher.info.on('bye', (_code, reason) => {
// console.log ('You have left the room. Reason: ${reason}');
});
pusher.info.on('pushstatistics', _stat => {
// console.log(_stat);
});
AlivcLivePusher.error
|
Evento |
Descrição |
||||||
|
system |
Erro do sistema. |
||||||
|
sdk |
Erro interno do SDK. |
||||||
Código de exemplo:
pusher.error.on('system', error => {
// console.log(error);
});
pusher.error.on('sdk', error => {
// console.log(error);
});
AlivcLivePusher.network
|
Evento |
Descrição |
||||||
|
connectionlost |
Desconectado. |
||||||
|
networkrecovery |
Rede recuperada. |
||||||
|
reconnectstart |
Reconexão iniciada. |
||||||
|
reconnectfail |
Falha na reconexão. |
||||||
|
reconnectsucceed |
Reconexão bem-sucedida. |
||||||
Código de exemplo:
pusher.network.on('connectionlost', () => {
// console.log ('A network exception occurs, which results in a disconnection.');
});
AlivcLivePlayer (recebimento de stream)
Lista de métodos
|
Método |
Descrição |
||||||
|
Inicia a reprodução de áudio e vídeo. |
|||||||
|
Reproduz áudio e vídeo em outro elemento. |
|||||||
|
Para a reprodução de áudio e vídeo. |
|||||||
|
Pausa a reprodução de áudio. |
|||||||
|
Pausa a reprodução de vídeo. |
|||||||
|
Retoma a reprodução de áudio. |
|||||||
|
Retoma a reprodução de vídeo. |
|||||||
|
Libera a instância do player. |
|||||||
Detalhes
-
startPlay: inicia a reprodução de áudio e vídeo.
/** * Start the playback of the audio and video streams. * @param url The streaming URL. Example: artc://live.aliyun.com/play/... * @param elementOrId The label or ID of the media resource. * @param secondaryElementOrId The label or ID of the media resource of the secondary stream. * @return {Promise<AlivcLivePlayInfo>} You can use AlivcLivePlayInfo to listen to related events. */ const playInfo = await player.startPlay(url, elementOrId, secondaryElementOrId);ImportanteEspecifique uma URL de streaming usada para co-streaming. Para obter informações sobre como gerar URLs para co-streaming, consulte Gerador de URL de co-streaming.
Espectadores comuns podem reproduzir o stream com o ApsaraVideo Player SDK for Web. Acesso rápido a um player web.
-
playAnotherElement: reproduz áudio e vídeo em outro elemento.
/** * Play the audio and video streams on another node. * @param elementOrId The label or ID of the media resource. * @param secondary Specifies whether to play the secondary stream. This parameter is optional. By default, only the primary stream is played. */ player.playAnotherElement(elementOrId); -
stopPlay: para a reprodução de áudio e vídeo.
/** * Stop the playback of the audio and video streams. * @param elementOrId The label or ID of the media resource. This parameter is optional. If you do not specify this parameter, playback of all media resources is stopped. * @return {Promise} */ await player.stopPlay(elementOrId); -
pauseAudioPlaying: pausa a reprodução de áudio.
/** * Pause the playback of the audio stream. */ player.pauseAudioPlaying(); -
pauseVideoPlaying: pausa a reprodução de vídeo.
/** * Pause the playback of the video stream. */ player.pauseVideoPlaying(); -
resumeAudioPlaying: retoma a reprodução de áudio.
/** * Resume the playback of the audio stream. */ player.resumeAudioPlaying(); -
resumeVideoPlaying: retoma a reprodução de vídeo.
/** * Resume the playback of the video stream. */ player.resumeVideoPlaying(); -
destroy: libera a instância do player.
/** * Release the stream pulling instance. You cannot use the instance after you release it. */ player.destroy();
AlivcLivePlayInfo
|
Evento |
Descrição |
||||||
|
canplay |
Stream pronto para reprodução. |
||||||
|
userleft |
Usuário remoto saiu da sala. |
||||||
|
statistics |
Estatísticas de reprodução. |
||||||
|
update |
Atualize o stream remoto. |
||||||
Código de exemplo:
playInfo.on('statistics', _stat => {
// console.log(_stat);
});
playInfo.on('userleft', () => {
// console.log ('The remote user leaves the room.');
});
playInfo.on('canplay', function () {
// console.log ('The remote stream can be played.');
});
playInfo.on('update', function (previousStatus) {
// console.log(previousStatus.mediaStream);
// console.log(previousStatus.secondaryMediaStream);
});