Todos os produtos
Search
Central de documentação

ApsaraVideo Live:Usar o Push SDK para Flutter

Última atualização: Jun 30, 2026

O Push SDK para Flutter permite adicionar ingestão de stream a aplicativos Flutter. Este guia aborda o fluxo de trabalho básico e fornece exemplos de uso para cada recurso.

Recursos

  • Suporta ingestão de stream via Real-Time Messaging Protocol (RTMP).

  • Compatível com ingestão de stream via Alibaba Real-Time Communication (ARTC) baseada em User Datagram Protocol (UDP).

  • Utiliza H.264 para codificação de vídeo e AAC para codificação de áudio.

  • Permite configurações personalizadas para controle de taxa de bits, resolução e modo de exibição.

  • Oferece suporte a diversas operações de câmera.

  • Inclui retoque em tempo real e efeitos de retoque personalizados.

  • Possibilita adicionar e remover adesivos animados como marcas d'água.

  • Aceita entradas externas de áudio e vídeo em diferentes formatos, como YUV e modulação por código de pulso (PCM).

  • Permite a ingestão de streams apenas de áudio, apenas de vídeo e a ingestão de stream em segundo plano.

  • Suporta música de fundo.

  • Captura snapshots de vídeo.

  • Conta com reconexão automática e tratamento de erros.

  • Implementa algoritmos de Controle Automático de Ganho (AGC), Redução Automática de Ruído (ANR) e Cancelamento de Eco Acústico (AEC).

  • Permite alternar entre os modos de codificação de software e hardware, aumentando a estabilidade do módulo de codificação.

Limitações

Observe as seguintes limitações:

  • Configure a orientação da tela antes da ingestão de stream. Não é possível girar a tela durante a transmissão ao vivo.

  • Desative a rotação automática de tela para ingestão de stream no modo paisagem.

  • No modo de codificação de hardware, o valor da resolução de saída deve ser um múltiplo de 16 para garantir compatibilidade com o codificador. Por exemplo, se você definir a resolução como 540p, a resolução de saída será 544 × 960. Ajuste o tamanho da tela do player com base na resolução de saída para evitar barras pretas.

Referência da API

Referência da API do Push SDK para Flutter

Procedimento

  1. Registrar o SDK

  2. Configurar parâmetros de ingestão de stream

  3. Iniciar a ingestão de stream

Uso dos recursos

Registrar o SDK

Antes do registro, configure a licença do SDK. O Push SDK para Flutter suporta a licença unificada. Para solicitar e configurar uma licença, consulte Integrar uma licença do Push SDK.

Registre o SDK antes de iniciar a ingestão de stream.

  1. Registre o SDK.

    AlivcLiveBase.registerSDK();
  2. Defina um listener para o registro.

    AlivcLiveBase.setListener(AlivcLiveBaseListener(
      onLicenceCheck: (AlivcLiveLicenseCheckResultCode result, String reason) {
        if (result == AlivcLiveLicenseCheckResultCode.success) {
          /// The SDK is registered.
        }
      },
    ));

Configurar parâmetros de ingestão de stream

Todos os parâmetros básicos possuem valores padrão. Recomendamos o uso desses valores.

/// Create an AlivcLivePusher instance.
AlivcLivePusher livePusher = AlivcLivePusher.init();

/// Create a Config object to associate AlivcLivePushConfig with AlivcLivePusher.
livePusher.createConfig();

/// Create an AlivcLivePushConfig instance.
AlivcLivePushConfig pusherConfig = AlivcLivePushConfig.init();

/// Configure stream ingest parameters.
/// Set the resolution to 540P.
pusherConfig.setResolution(AlivcLivePushResolution.resolution_540P);
/// Specify the frame rate. We recommend that you set it to 20 frames per second (FPS).
pusherConfig.setFps(AlivcLivePushFPS.fps_20);
/// Specify whether to enable adaptive bitrate streaming. The default value is true.
pusherConfig.setEnableAutoBitrate(true);
/// Specify the group of pictures (GOP) size. A larger value indicates a higher latency. We recommend that you set it to a number from 1 to 2.
pusherConfig.setVideoEncodeGop(AlivcLivePushVideoEncodeGOP.gop_2);
/// Specify the reconnection duration. The value cannot be less than 1000. Unit: milliseconds. We recommend that you use the default value.
pusherConfig.setConnectRetryInterval(2000);
/// Disable the mirroring mode for preview.
pusherConfig.setPreviewMirror(false);
/// Set the stream orientation to portrait.
pusherConfig.setOrientation(AlivcLivePushOrientation.portrait);

Iniciar a ingestão de stream

  1. Crie um mecanismo livePusher.

    livePusher.initLivePusher();
  2. Registre listeners para eventos de ingestão de stream.

    /// Set the listener for the stream ingest status.
    livePusher.setInfoDelegate();
    /// Set the listener for stream ingest errors.
    livePusher.setErrorDelegate();
    /// Set the listener for the network status during stream ingest.
    livePusher.setNetworkDelegate();
  3. Configure callbacks relacionados à ingestão de stream.

    /// Listener for stream ingest errors
    /// Configure the callback for SDK errors
    livePusher.setOnSDKError((errorCode, errorDescription) {});
    /// Configure the callback for system errors
    livePusher.setOnSystemError((errorCode, errorDescription) {});
    
    /// Listener for the stream ingest status
    /// Configure the callback for preview start
    livePusher.setOnPreviewStarted(() {});
    /// Configure the callback for preview stop
    livePusher.setOnPreviewStoped(() {});
    /// Configure the callback for first frame rendering
    livePusher.setOnFirstFramePreviewed(() {});
    /// Configure the callback for start of stream ingest
    livePusher.setOnPushStarted(() {});
    /// Configure the callback for pause of camera stream ingest
    livePusher.setOnPushPaused(() {});
    /// Configure the callback for resume of camera stream ingest
    livePusher.setOnPushResumed(() {});
    /// Configure the callback for restart of stream ingest
    livePusher.setOnPushRestart(() {});
    /// Configure the callback for end of stream ingest
    livePusher.setOnPushStoped(() {});
    
    /// Listener for the network status during stream ingest
    /// Configure the callback for failed connections
    livePusher.setOnConnectFail((errorCode, errorDescription) {});
    /// Configure the callback for network recovery
    livePusher.setOnConnectRecovery(() {});
    /// Configure the callback for disconnection
    livePusher.setOnConnectionLost(() {});
    /// Configure the callback for poor network connections
    livePusher.setOnNetworkPoor(() {});
    /// Configure the callback for failed reconnections
    livePusher.setOnReconnectError((errorCode, errorDescription) {});
    /// Configure the callback for reconnection start
    livePusher.setOnReconnectStart(() {});
    /// Configure the callback for successful reconnection
    livePusher.setOnReconnectSuccess(() {});
  4. Crie uma visualização de prévia para a ingestão de stream.

    var x = 0.0; // The custom value
    var y = 0.0; // The custom value
    var width = MediaQuery.of(context).size.width; // The custom value
    var height = MediaQuery.of(context).size.height; // The custom value
    AlivcPusherPreview pusherPreviewView = AlivcPusherPreview(
          onCreated: _onPusherPreviewCreated,
          x: x,
          y: y,
          width: width,
          height: height);
      return Container(
            color: Colors.black,
            width: width,
            height: height,
            child: pusherPreviewView);
  5. Inicie a prévia.

    /// Callback for preview creation
    _onPusherPreviewCreated(id) {
         /// Start preview
        livePusher.startPreview();
    }
    Nota

    Suponha que a orientação da tela do projeto Flutter seja retrato e você chame setOrientation para definir a orientação como paisagem. Após criar a prévia e chamar startPreview para iniciá-la, o vídeo pode não preencher totalmente a janela de prévia. Recomendamos adicionar um pequeno atraso antes de invocar startPreview.

    Por exemplo: Future.delayed(Duration(milliseconds: 100));

  6. Inicie a ingestão de stream. A ingestão só pode ser iniciada após o sucesso da prévia.

    String pushURL = "Test ingest URL (rtmp://......)"; 
    livePusher.startPushWithURL(pushURL);
    Nota
    • URLs de ingestão RTMP e RTS (artc://) são suportadas. Para gerar URLs de ingestão, consulte Gerar URLs de stream ao vivo.

    • O ApsaraVideo Live não suporta a ingestão simultânea de múltiplos streams para a mesma URL. A segunda solicitação de ingestão será rejeitada.

Métodos relacionados à ingestão

/// Pause stream ingest from the camera. You can call setPauseImg to configure the image displayed during the pause. Then, call the pause method to switch from camera feeds to the specified image. The audio stream continues to be ingested.
livePusher.pause();
/// Resume stream ingest to switch from image to camera feeds. The audio stream continues to be ingested.
livePusher.resume();
/// Stop a stream that is being ingested.
livePusher.stopPush();
/// Stop preview. However, this operation does not take effect for a stream that is being ingested. When preview is stopped, the preview window is frozen at the last frame.
livePusher.stopPreview();
/* Restart stream ingest when the stream is being ingested or when an error callback is received. All resources in AlivcLivePusher are reinitialized, including preview and ingestion. If an error occurs, you can call this method or the reconnectPushAsync method to restart stream ingest. You can also call the destroy method to destroy the stream ingest instance. */
livePusher.restartPush();
/* Reconnect and repush the RTMP stream during streaming or network error state (setNetworkDelegate). In the error state, you can also call destroy to dispose the instance.*/
livePusher.reconnectPushAsync();
/// Stop stream ingest and preview. After you call this method, all resources related to AlivcLivePusher are disposed.
livePusher.destory();

Métodos relacionados à câmera

/// Switch between the front and rear cameras.
livePusher.switchCamera();
/// Enable or disable flash. You cannot enable flash for the front camera.
livePusher.setFlash(false);

/// Adjust the focal length to zoom in or out. If you set the input parameter to a positive number, the system increases the focal length. If you set the input parameter to a negative number, the system decreases the focal length.
double max = await livePusher.getMaxZoom();
livePusher.setZoom(min(1.0, max));

/// Configure manual focus.
/// The autoFocus parameter specifies whether to enable autofocus. This parameter takes effect only for this call. Whether autofocus is enabled depends on the setAutoFocus method.
double pointX = 50.0; // The custom value
double pointY = 50.0; // The custom value
bool autoFocus = true;
livePusher.focusCameraAtAdjustedPoint(pointX, pointY, autoFocus);

/// Disable autofocus.
livePusher.setAutoFocus(false);
/// Disable the mirroring mode for preview.
livePusher.setPreviewMirror(false);
/// Disable the mirroring mode for stream ingest.
livePusher.setPushMirror(false);

Ingerir uma imagem

É possível ingerir uma imagem estática quando o aplicativo está em segundo plano ou quando a taxa de bits está baixa.

Quando o aplicativo vai para segundo plano, a ingestão de vídeo é pausada por padrão e apenas o áudio continua. Você pode exibir uma imagem para informar aos espectadores que o streamer retornará em breve.

/// Specify the image that is ingested during the pause.
String pauseImagePath = "xxxx"; // xxxx specifies the path of the image.
pusherConfig.setPauseImg(pauseImagePath);

Também é possível exibir uma imagem em condições de rede ruins para evitar travamentos:

/// Specify the image that is ingested in poor network conditions.
String networkPoorImagePath = "xxxx"; // xxxx specifies the path of the image.
pusherConfig.setNetworkPoorImg(networkPoorImagePath);

Configurar o modo de exibição da prévia

Os seguintes modos de exibição de prévia estão disponíveis. O modo de prévia não afeta a ingestão de stream.

  • AlivcPusherPreviewDisplayMode.preview_scale_fill: O vídeo preenche toda a janela de prévia. Se as proporções do vídeo e da janela forem inconsistentes, ocorrerá deformação da imagem.

  • AlivcPusherPreviewDisplayMode.preview_aspect_fit: A proporção original do vídeo é preservada. Caso haja diferença nas proporções, barras pretas aparecerão na janela de prévia.

  • AlivcPusherPreviewDisplayMode.preview_aspect_fill: O vídeo é cortado para ajustar-se à janela de prévia quando as proporções diferem.

Código de exemplo:

/// Set the preview display mode.
pusherConfig.setPreviewDisplayMode(AlivcPusherPreviewDisplayMode.preview_aspect_fit);

Configurar a qualidade do vídeo

Três modos de qualidade de vídeo estão disponíveis: Prioridade de Resolução, Prioridade de Fluidez e Personalizado.

Importante

Para configurar a qualidade do vídeo, ative o controle de taxa de bits: pusherConfig.setEnableAutoBitrate(true);

Prioridade de Resolução (padrão)

O SDK configura automaticamente os parâmetros de taxa de bits para priorizar a qualidade do vídeo.

pusherConfig.setQualityMode(AlivcLivePushQualityMode.resolution_first);

Prioridade de Fluidez

O SDK ajusta automaticamente os parâmetros de taxa de bits para priorizar a suavidade do stream.

pusherConfig.setQualityMode(AlivcLivePushQualityMode.fluency_first);

Modo personalizado

O SDK utiliza os valores inicial, mínimo e alvo de taxa de bits especificados por você.

  • TargetVideoBitrate: Em boas condições de rede, a taxa de bits aumenta gradualmente até atingir o valor alvo, melhorando a qualidade do vídeo.

  • MinVideoBitrate: Em condições de rede ruins, a taxa de bits diminui gradualmente até o mínimo para evitar travamentos.

  • InitialVideoBitrate: Taxa de bits inicial quando a transmissão ao vivo começa.

pusherConfig.setQualityMode(AlivcLivePushQualityMode.custom);
pusherConfig.setInitialVideoBitrate(1000);
pusherConfig.setMinVideoBitrate(600);
pusherConfig.setTargetVideoBitrate(1400);

Consulte as seguintes configurações recomendadas de taxa de bits:

  • Configurações recomendadas para o modo Prioridade de Resolução

    Resolução

    Taxa de bits inicial

    Taxa de bits mínima

    Taxa de bits alvo

    360P

    600

    300

    1000

    480P

    800

    300

    1200

    540P

    1000

    600

    1400

    720P

    1500

    600

    2000

    1080P

    1800

    1200

    2500

  • Configurações sugeridas para o modo Prioridade de Fluidez

    Resolução

    Taxa de bits inicial

    Taxa de bits mínima

    Taxa de bits alvo

    360P

    400

    200

    600

    480P

    600

    300

    800

    540P

    800

    300

    1000

    720P

    1000

    300

    1200

    1080P

    1500

    1200

    2200

Configurar resolução adaptativa

Quando ativada, a resolução adaptativa reduz automaticamente a resolução do stream em condições de rede ruins para manter a fluidez e a qualidade:

/// Enable adaptive resolution。
pusherConfig.setEnableAutoResolution(true);
Importante
  • A resolução adaptativa entra em vigor apenas quando o modo de qualidade de vídeo está definido como Prioridade de Resolução ou Prioridade de Fluidez.

  • Alguns players podem não suportar resolução dinâmica. Recomendamos o uso do ApsaraVideo Player.

Configurar música de fundo

/// Start the playback of background music。
String musicPath = "xxxx"; // xxxx specifies the path in which the music resources are stored.
livePusher.startBGMWithMusicPathAsync(musicPath);
/// Stop the playback of background music. If you want to change the background music, call the method that is used to start the playback of background music. You do not need to stop the playback of the current background music.
livePusher.stopBGMAsync();
/// Pause the playback of background music. You can call this method only after the playback of background music starts.
livePusher.pauseBGM();
/// Resume the playback of background music. You can call this method only after the playback of background music is paused.
livePusher.resumeBGM();
/// Enable looping.
livePusher.setBGMLoop(true);
/// Configure denoising. When enabled, the system filters out non-vocal parts from the collected audio. This feature may slightly reduce the volume of the human voice. We recommend that you allow your users to determine whether to enable this feature. By default, this feature is disabled.
livePusher.setAudioDenoise(true);
/// Configure in-ear monitoring. In-ear monitoring is suitable for karaoke scenarios. When enabled, headphone users can hear their voice. When disabled, they cannot hear their voice on headphones. This parameter does not take effect if no headphones are detected. 
livePusher.setBGMEarsBack(true);
/// Specify the volume of the background music in the mixed audio.
livePusher.setBGMVolume(50); // Valid values: 0 to 100. Default value: 50
/// Specify the volume of the human voice in the mixed audio.
livePusher.setCaptureVolume(50); // Valid values: 0 to 100. Default value: 50
/// Configure muting. If you enable this feature, the background music and human voice are muted. To separately mute the background music or human voice, call the method that is used to configure the volume.
livePusher.setMute(true);

Configure callbacks relacionados à música de fundo:

/// Configure the callback for end of playback of background music.
livePusher.setOnBGMCompleted(() {});
/// Configure the callback for timeout of the download of background music.
livePusher.setOnBGMDownloadTimeout(() {});
/// Configure the callback for failed playback of background music.
livePusher.setOnBGMOpenFailed(() {});
/// Configure the callback for paused playback of background music.
livePusher.setOnBGMPaused(() {});
/// Configure the callback for playback progress.
livePusher.setOnBGMProgress((progress, duration) {});
/// Configure the callback for resumed playback of background music.
livePusher.setOnBGMResumed(() {});
/// Configure the callback for start of playback of background music.
livePusher.setOnBGMStarted(() {});
/// Configure the callback for stop of playback of background music.
livePusher.setOnBGMStoped(() {});

Capturar snapshots

/// Capture a snapshot.
String dir = "xxxx"; // xxxx specifies the path in which snapshots are stored.
if (Platform.isIOS) {
    /// dir parameter: On iOS, the path is a relative path. A custom directory is automatically generated in the system sandbox. If you set this parameter to "", snapshots are stored in the root directory of the system sandbox.
    /// dirTypeForIOS parameter: Optional. If you do not specify this parameter, snapshots are stored in the [document] directory of the system sandbox.
    livePusher.snapshot(1, 0, dir, dirTypeForIOS: AlivcLiveSnapshotDirType.document);
} else {
    livePusher.snapshot(1, 0, dir);
}
/// Set the listener for snapshot capture. You can call this method only after you call snapshot.
livePusher.setSnapshotDelegate();

/// Configure callbacks related to snapshot capture.
livePusher.setOnSnapshot((saveResult, savePath, {dirTypeForIOS}) {
  	// The callback that is triggered when a snapshot is stored.
    if (saveResult == true) {
      if (Platform.isIOS) {
        // Construct the full path of snapshots in the system sandbox. Format: dirTypeForIOS + savePath.
      } else {
        // Obtain the path of snapshots based on the value of savePath.
      }
    }
  });

Configurar marcas d'água

O Push SDK para Android permite adicionar uma ou mais marcas d'água no formato PNG. Código de exemplo:

String watermarkBundlePath = "xxxx"; //xxxx specifies the path in which the watermark image is stored.
double coordX = 0.1;
double coordY = 0.1;
double width = 0.3;
/// Add a watermark.
livePusher.addWatermark(watermarkBundlePath, coordX, coordY, width);

Onde:

  • coordX e coordY são valores relativos que determinam a posição da marca d'água. coordX=0,1 indica que a borda esquerda da marca d'água está posicionada em 10% da largura do stream. Quando a resolução é 540 x 960, a posição x corresponde a 540 x 0,1 = 54 pixels.

  • width define a largura da marca d'água em relação à largura do stream. A altura é dimensionada proporcionalmente.

Nota
  • Para adicionar uma marca d'água de texto, converta o texto em uma imagem PNG e, em seguida, chame este método para adicioná-la.

  • Para garantir clareza e suavidade nas bordas da marca d'água, recomendamos usar uma imagem fonte com o mesmo tamanho da sua configuração. Por exemplo, se a resolução do vídeo de saída for 544 × 940 e a largura da marca d'água for definida como 0.1f, a largura recomendada da imagem fonte é 544 × 0,1f = 54,4 pixels.

Enviar fontes externas de áudio/vídeo

O Push SDK para Android suporta a ingestão de fontes externas de áudio/vídeo, como um arquivo de vídeo.

Antes da ingestão, ative a entrada personalizada de áudio e vídeo.

/// Enable custom audio and video input.
pusherConfig.setExternMainStream(true);
/// Specify the color format for video data. In this example, YUVNV21 is used. You can also use other formats based on your business requirements.
pusherConfig.setExternVideoFormat(AlivcLivePushVideoFormat.YUVNV21);
/// Specify the bit depth format for audio data. In this example, S16 is used. You can also use other formats based on your business requirements.
pusherConfig.setExternMainStream(AlivcLivePushAudioFormat.S16);

Após ativar a entrada personalizada, envie streams externos de áudio e vídeo.

Enviar dados externos de vídeo

/// Only continuous buffer data in the YUV or RGB format can be sent by using the sendVideoData method. You can specify the video buffer, length, width, height, timestamp, and rotation angle.
Uint8List bufferData = xxxx; // xxxx indicates the continuous video buffer data in the Uint8List format.
int width = 720; // The video width.
int height = 1280; // The video height.
int dataSize = xxxx; // xxxx indicates the size of the data.
int pts = xxxx; // xxxx indicates the timestamp in microseconds.
int rotation = 0; // The rotation angle.
livePusher.sendVideoData(bufferData, width, height, size, pts, rotation);

Enviar dados externos de áudio

/// Only continuous buffer data in the PCM format can be sent by using the sendPCMData method. You can specify the audio buffer, length, and timestamp.
Uint8List bufferData = xxxx; // xxxx indicates the continuous audio buffer data in the Uint8List format.
int dataSize = xxxx; // xxxx indicates the size of the data.
int sampleRate = xxxx; // xxxx indicates the audio sample rate.
int channel = 0; // The number of sound channels.
int pts = xxxx; // xxxx indicates the timestamp in microseconds.
livePusher.sendPCMData(bufferData, size, sampleRate, channel, pts);

Obter o número da versão do Push SDK nativo

/// Obtain the version number of the native Push SDK.
String sdkVersion = await AlivcLiveBase.getSdkVersion();

Configurar logs

/// Enable log printing in the console.
AlivcLiveBase.setConsoleEnable(true);
/// Set the log level to Debug.
AlivcLiveBase.setLogLevel(AlivcLivePushLogLevel.debug);

/// Specify the maximum size of each shard. The total log size is five times the maximum shard size.
const int saveLogMaxPartFileSizeInKB = 100 * 1024 * 1024;
/// Log path.
String saveLogDir = "TODO";
/// Specify the log path and log shard size。
AlivcLiveBase.setLogPath(saveLogDir, saveLogMaxPartFileSizeInKB);

Redefinir o objeto config (iOS)

Chame este método para limpar as configurações do AlivcLivePushConfig no iOS. A próxima instância do AlivcLivePusher usará as configurações padrão.

Recomendamos chamar este método após invocar o método destroy para o AlivcLivePusher.

/// Reset the Config object on iOS.
livePusher.destroyConfigForIOS();

Adicionar efeitos de retoque

Os efeitos de retoque são fornecidos por meio do plug-in flutter_livepush_beauty_plugin, localizado no diretório example\plugins do pacote SDK.

Nota

O plug-in de retoque não é lançado separadamente.

/// 1. Initialize the retouching object.
AlivcLiveBeautyManager beautyManager = AlivcLiveBeautyManager.init();
beautyManager.setupBeauty();
/// 2. Show the retouching panel.
beautyManager.showPanel();
/// 3. Close the retouching panel (for Android).
beautyManager.hidePanel();
/// 4. Dispose the retouching object.
beautyManager.destroyBeauty();

Perguntas frequentes

Como solucionar falhas na ingestão de stream?

Utilize a ferramenta de solução de problemas para verificar se a URL de ingestão é válida.

Como obter informações sobre streams ingeridos?

Acesse a página de Gerenciamento de Streams e visualize os streams de áudio e vídeo ingeridos em Active Streams.

Como reproduzir um stream?

Após iniciar a ingestão de stream, utilize um player (como ApsaraVideo Player, FFplay ou VLC) para testar o pull do stream. Para obter URLs de reprodução, consulte Gerar URLs de stream ao vivo.