Todos os produtos
Search
Central de documentação

ApsaraVideo VOD:Recursos avançados

Última atualização: Jul 04, 2026

Use os recursos avançados do Android Player SDK, incluindo reprodução de playlists, legendas, download de vídeo e reprodução criptografada. Referência da API.

Importante

Para executar a demonstração, baixe-a e siga as instruções em Executar a demonstração para compilar e executar o projeto.

Verificação de licença da Professional Edition

Nota

Alguns recursos do player exigem uma licença da Professional Edition. Verifique os recursos suportados em Detalhes dos recursos do Player SDK. Para usar esses recursos, conclua a autorização conforme descrito em Obter uma licença do Player SDK.

Defina um listener antes que o aplicativo inicie ou antes de chamar qualquer API do player:

import com.aliyun.private_service.PrivateService;

PrivateService.setOnPremiumLicenseVerifyCallback(new PrivateService.OnPremiumLicenseVerifyCallback() {
    @Override
    public void onPremiumLicenseVerifyCallback(PrivateService.PremiumBizType type, boolean isValid, String errorMsg) {
        Log.d(TAG, "onPremiumLicenseVerifyCallback: " + type + " isValid: " + isValid + " errorMsg: " + errorMsg);
    }
});

O PremiumBizType enumera os recursos profissionais. Ao usar um recurso relacionado, o player verifica a licença e retorna o resultado por meio deste callback. Se isValid for falso, errorMsg conterá o motivo.

Reprodução

Reprodução de playlist

O Android Player SDK oferece reprodução de playlists com pré-carregamento, melhorando significativamente a velocidade de início para vídeos curtos.

Procedimento

  1. Crie um player.

    Crie uma instância AliListPlayer usando a classe AliPlayerFactory. Exemplo:

    AliListPlayer aliListPlayer;
    .....
    aliListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
    aliListPlayer.setTraceId("traceId");  // traceId is a unique identifier for the device or user, typically IMEI or IDFA.
  2. Opcional: Defina listeners.

    Os listeners são opcionais, mas recomendados. Sem eles, não é possível receber notificações de eventos. Listeners principais: OnPreparedListener, OnErrorListener, OnCompletionListener, OnLoadingStatusListener e OnInfoListener.

    Expandir para visualizar o código

    aliListPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
        @Override
        public void onCompletion() {
            // Playback completed.
        }
    });
    aliListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            // Error occurred.
        }
    });
    aliListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        @Override
        public void onPrepared() {
            // Preparation succeeded.
        }
    });
    aliListPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(int width, int height) {
            // Video resolution changed.
        }
    });
    aliListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
        @Override
        public void onRenderingStart() {
            // First frame rendered.
        }
    });
    aliListPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
        @Override
        public void onInfo(int type, long extra) {
            // Other information events. Type includes: loop playback started, buffer position, current playback position, autoplay started, etc.
        }
    });
    aliListPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
        @Override
        public void onLoadingBegin() {
            // Buffering started.
        }
        @Override
        public void onLoadingProgress(int percent, float kbps) {
            // Buffering progress.
        }
        @Override
        public void onLoadingEnd() {
            // Buffering ended.
        }
    });
    aliListPlayer.setOnSeekCompleteListener(new IPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete() {
            // Seeking completed.
        }
    });
    aliListPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
        @Override
        public void onSubtitleShow(long id, String data) {
            // Show subtitle.
        }
        @Override
        public void onSubtitleHide(long id) {
            // Hide subtitle.
        }
    });
    aliListPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
        @Override
        public void onChangedSuccess(TrackInfo trackInfo) {
            // Audio/video stream or definition switched successfully.
        }
        @Override
        public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
            // Audio/video stream or definition switch failed.
        }
    });
    aliListPlayer.setOnStateChangedListener(new IPlayer.OnStateChangedListener() {
        @Override
        public void onStateChanged(int newState) {
            // Player state changed.
        }
    });
    aliListPlayer.setOnSnapShotListener(new IPlayer.OnSnapShotListener() {
        @Override
        public void onSnapShot(Bitmap bm, int with, int height) {
            // Screenshot taken.
        }
    });
  3. Defina o número de itens pré-carregados.

    Configure a quantidade de itens pré-carregados para aumentar a velocidade de início. Exemplo:

    // Set the number of preloaded items. The total number of loaded items is 1 + count × 2.
    aliListPlayer.setPreloadCount(int count);
  4. Adicione ou remova múltiplas fontes de reprodução.

    A reprodução de playlist suporta fontes Vid (VidSts e VidPlayAuth) e UrlSource. Exemplos:

    • URL: Endereço de reprodução de terceiros ou do Alibaba Cloud VOD. Para obter um endereço de reprodução do Alibaba Cloud, chame GetPlayInfo. Integre o VOD server SDK para obter endereços e evitar a autoassinatura. Portal do Desenvolvedor.

    • Vid: O ID de áudio e vídeo. Você pode obter esse ID no console (caminho: Media Library > Audio/Video) ou usando a API do servidor (Pesquisar informações de mídia) após carregar o áudio ou vídeo.

    // Add a Vid playback source.
    aliListPlayer.addVid(String videoId, String uid);
    // Add a UrlSource playback source.
    aliListPlayer.addUrl(String url, String uid);
    // Remove a source.
    aliListPlayer.removeSource(String uid);
    Nota

    O uid identifica exclusivamente um vídeo. Vídeos com o mesmo uid são tratados como idênticos. Se ocorrer mistura de streams durante a reprodução, verifique se o mesmo uid está definido em diferentes views. O uid pode ser qualquer string.

  5. Defina a view de exibição.

    O player suporta SurfaceView e TextureView. Escolha uma opção:

    • Configure o SurfaceView. Exemplo:

      Expandir para visualizar o código

      SurfaceView surfaceView = findViewById(R.id.surface_view);
      surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
          @Override
          public void surfaceCreated(SurfaceHolder holder) {
              aliListPlayer.setSurface(holder.getSurface());
          }
      
          @Override
          public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
              aliListPlayer.surfaceChanged();
          }
      
          @Override
          public void surfaceDestroyed(SurfaceHolder holder) {
              aliListPlayer.setSurface(null);
          }
      });
    • Configure o TextureView. Exemplo:

      Expandir para visualizar o código

      TextureView textureView = findViewById(R.id.texture_view);
      textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
          @Override
          public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
              aliListPlayer.setSurface(new Surface(surface));
          }
      
          @Override
          public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
              aliListPlayer.surfaceChanged();
          }
      
          @Override
          public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
              aliListPlayer.setSurface(null);
              return false;
          }
      
          @Override
          public void onSurfaceTextureUpdated(SurfaceTexture surface) {
      
          }
      });
  6. Reproduza uma fonte de vídeo.

    Após adicionar uma ou mais fontes de reprodução e ativar a reprodução automática, chame moveTo para reproduzir automaticamente uma fonte de vídeo específica. Exemplo:

    Expandir para visualizar o código

    // Enable autoplay.
    aliListPlayer.setAutoPlay(true);
    
    // Use this method for URL sources.
    aliPlayer.moveTo(String uid);
    // Use this method for Vid sources. You must pass stsInfo, which includes the STS temporary credentials and temporary AccessKey pair. Obtain these credentials in advance. For more information, see Create a RAM role and perform STS temporary authorization.
    aliPlayer.moveTo(String uid, StsInfo info);
  7. Reproduza o vídeo anterior ou seguinte.

    • Após chamar moveTo para reproduzir uma fonte de vídeo, chame moveToPrev e moveToNext para reproduzir o vídeo anterior ou seguinte, usando a fonte de vídeo especificada por moveTo como âncora. Exemplo:

      Nota

      Ao alternar fontes de vídeo chamando moveTo, moveToNext ou métodos similares baseados na mesma view, podem ocorrer cintilações ou telas pretas. Nesse caso, ao inicializar o listPlayer, configure o campo PlayerConfig mClearFrameWhenStop como false e chame setConfig para aplicar a configuração.

      Expandir para visualizar o código

      // Enable autoplay.
      aliListPlayer.setAutoPlay(true);
      
      // Move to the next video. Note: This method applies only to URL sources and not to Vid playback.
      aliListPlayer.moveToNext();
      // Move to the previous video. Note: This method applies only to URL sources and not to Vid playback.
      aliListPlayer.moveToPrev();
      // Move to the next video. Note: This method applies only to Vid playback.
      aliListPlayer.moveToNext(StsInfo info);
      // Move to the previous video. Note: This method applies only to Vid playback.
      aliListPlayer.moveToPrev(StsInfo info);
Nota

Para uma melhor experiência de reprodução de playlist, use a solução de dramas curtos. Desenvolvimento de cliente para dramas curtos.

Reprodução de vídeos com transparência

Visão geral do recurso

O ApsaraVideo Player SDK suporta renderização de canal alfa para animações de presentes transparentes. Em cenários de transmissão ao vivo, essas animações são reproduzidas sem obscurecer o conteúdo ao vivo.

Limites

O Integrated SDK versão 6.8.0 ou posterior, ou o Player SDK versão 6.9.0 ou posterior, suporta renderização transparente.

Benefícios

Vídeos MP4 com transparência oferecem melhor qualidade de animação, tamanhos de arquivo menores, maior compatibilidade e eficiência de desenvolvimento aprimorada em comparação com APNG ou IXD.

  1. Melhor qualidade de animação: O MP4 retém detalhes e cores originais com mais precisão do que APNG ou IXD.

  2. Tamanho de arquivo reduzido: O MP4 comprime de forma mais eficiente, melhorando a velocidade de carregamento e reduzindo o consumo de largura de banda.

  3. Maior compatibilidade: O formato MP4 é universalmente suportado em dispositivos e navegadores.

  4. Eficiência de desenvolvimento elevada: Os desenvolvedores não precisam implementar lógicas complexas de análise e renderização.

Código de exemplo

Adicione a seguinte interface: Defina o modo alfa (posição do canal alfa no ativo de vídeo: topo, base, esquerda, direita). O valor padrão é None.

Nota
  • A posição do canal alfa no ativo deve corresponder à configuração do parâmetro setAlphaRenderMode.

  • O tamanho da playerview deve ser proporcional à resolução do ativo.

/**
 * Set alpha render mode.
 *
 * @param alphaRenderMode The specified alpha render mode. See {@link AlphaRenderMode}.
 */
abstract public void setAlphaRenderMode(AlphaRenderMode alphaRenderMode);
//--------------View usage-------------
// For View, transparency must be set.
//TextureView
TextureView aliplayerView; // View used for playback.
aliplayerView.setOpaque(false);

//SurfaceView
SurfaceView aliplayerView; // View used for playback.
aliplayerView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
aliplayerView.setZOrderOnTop(true); // Place SurfaceView at the top of the display window.

//-----------AliPlayer usage-----------
// Set alpha mode.
aliPlayer.setAlphaRenderMode(IPlayer.AlphaRenderMode.RENDER_MODE_ALPHA_AT_RIGHT);
// Set the asset corresponding to the alpha mode.
UrlSource urlSource = new UrlSource();
urlSource.setUri("https://alivc-player.oss-cn-shanghai.aliyuncs.com/video/%E4%B8%9A%E5%8A%A1%E9%9C%80%E6%B1%82%E6%A0%B7%E6%9C%AC/alpha%E9%80%9A%E9%81%93/alpha_right.mp4");
aliPlayer.setDataSource(urlSource);
aliPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
    @Override
    public void onCompletion() {
        // Optional: If transition issues occur after single-instance playback completes, clear the screen.
        aliPlayer.clearScreen();
    }
}
aliPlayer.setAutoPlay(true);
aliPlayer.prepare();

Legendas externas

Nota

Para exemplos de código detalhados, consulte o módulo API-Example Demonstração e troca de legendas externas (ExternalSubtitle). Este projeto de exemplo baseado em Java para o ApsaraVideo Player SDK para Android ajuda os desenvolvedores a dominar rapidamente os principais recursos de integração do SDK.

O Android Player SDK suporta a adição e troca de legendas externas nos formatos SRT, SSA, ASS e VTT.

  1. Crie uma view para exibir legendas.

    Crie diferentes views com base no formato da legenda.

    Expandir para visualizar o código

    // For displaying SRT and VTT subtitles.
    SubtitleView subtitleView = new SubtitleView(getContext());
    // For player V7.6.0 and later, we recommend using VttSubtitleView to display SRT and VTT subtitles.
    VttSubtitleView vttSubtitleView = new VttSubtitleView(getContext());
    // For displaying ASS and SSA subtitles.
    AssSubtitleView assSubtitleView = new AssSubtitleView(getContext());
    // Add the subtitle view to the layout.
    viewGroup.addView(assSubtitleView);

    Ao integrar o player V7.6.0 ou posterior e usar VttSubtitleView para exibir legendas SRT e VTT, defina o seguinte listener:

    // Required for player 7.6.0 and later.
    mAliPlayer.setOnVideoSizeChangedListener(new IPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(int width, int height) {
            int viewWidth = getWidth();
            int viewHeight = getHeight();
            IPlayer.ScaleMode mode = mVideoListPlayer.getScaleMode();
            SubTitleBase.VideoDimensions videoDimensions = SubTitleBase.getVideoDimensionsWhenRenderChanged(width, height, viewWidth, viewHeight, mode);
            vttSubtitleView.setVideoRenderSize(videoDimensions.videoDisplayWidth, videoDimensions.videoDisplayHeight);
        }
    });
  2. Adicione legendas.

    Importante

    Defina os arquivos de legenda no callback onPrepared.

    mAliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
        @Override
        public void onPrepared() {
            // Set subtitles (must be done in onPrepared).
            mAliPlayer.addExtSubtitle(EXT_SUBTITLE_URL);
        }
    });
  3. Defina listeners relacionados às legendas.

    Expandir para visualizar o código

    mAliPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
                @Override
                public void onSubtitleExtAdded(int trackIndex, String url) {
                    // trackIndex: subtitle index; true: show the subtitle; false: hide the subtitle.
                    mAliPlayer.selectExtSubtitle(trackIndex, true);
                }
    
                @Override
                public void onSubtitleShow(int trackIndex, long id, String data) {
                    // Subtitle.
                    SubtitleView.Subtitle subtitle = new SubtitleView.Subtitle();
                    subtitle.id = String.valueOf(id);
                    subtitle.content = data;
                    // Show subtitle.
                    mSubtitleView.show(subtitle);
                }
    
                @Override
                public void onSubtitleHide(int trackIndex, long id) {
                    // Remove subtitle.
                    mSubtitleView.dismiss(String.valueOf(id));
                }
    
                @Override
                public void onSubtitleHeader(int trackIndex, String header) {
                }
            }
        );

Legendas externas (renderização personalizada baseada em componentes de renderização)

O suporte completo para legendas externas WebVTT é implementado usando VttSubtitleView e WebVttResolver, permitindo a personalização flexível do tamanho da fonte, cor e fontes específicas das legendas.

Nota

Cenários aplicáveis:

  • Personalização de estilos de legendas WebVTT.

  • Integração do ApsaraVideo Player SDK versão 7.11.0 ou posterior.

Importante

Pré-requisitos:

  • Arquivos de fonte (.ttf) colocados no diretório assets/fonts/ do seu projeto.

  • minSdk do projeto ≥ 21 (recomendado).

  • Listeners de legenda adicionados e conteúdo WebVTT acessível.

  1. Crie CustomStyleWebVttResolver e implemente WebVttResolver.

    public class CustomStyleWebVttResolver extends WebVttResolver {
    
        // Implement creation method.
        public CustomStyleWebVttResolver(Context context) {
            super(context);
            // Initialize fonts and other resources here later.
        }
    }
  2. Substitua applyTextSpans para personalizar estilos.

    Este método é chamado depois que a classe pai analisa os estilos básicos, permitindo o processamento secundário das legendas.

    • Método 1: Modifique VttContentAttribute e chame o método da classe pai.

      /**
       * Override text style application logic to implement custom style effects.
       * This method is called after the parent class parses basic styles, allowing secondary processing of font size, color, and other attributes.
       *
       * @param spannableStringBuilder Used to build styled text.
       * @param vttContentAttribute Style attribute object for the current text segment (includes font, color, size, etc.).
       * @param start Start position for style application (inclusive).
       * @param end End position for style application (exclusive).
       */
      @Override
      protected void applyTextSpans(SpannableStringBuilder spannableStringBuilder, VttContentAttribute vttContentAttribute, int start, int end) {
          // Set.
          // Save original font size (in px) for later adjustment.
          // Default font size is 0.0533f times video height.
          double originalFontSizePx = vttContentAttribute.fontSizePx;
      
          // Double the font size.
          vttContentAttribute.fontSizePx = originalFontSizePx * 2;
          
          // Change font color to red.
          vttContentAttribute.mPrimaryColour = Color.argb(255, 255, 0, 0);
      
          // Call parent class method to apply text.
          super.applyTextSpans(spannableStringBuilder, vttContentAttribute, start, end);
      }
    • Opere diretamente sobre SpannableStringBuilder para modificar estilos WebVTT diretamente.

      Importante

      Este método pode causar perda de estilos nativos do WebVTT.

      /**
       * Override text style application logic to implement custom style effects.
       * This method is called after the parent class parses basic styles, allowing secondary processing of font size, color, and other attributes.
       *
       * @param spannableStringBuilder Used to build styled text.
       * @param vttContentAttribute Style attribute object for the current text segment (includes font, color, size, etc.).
       * @param start Start position for style application (inclusive).
       * @param end End position for style application (exclusive).
       */
      @Override
      protected void applyTextSpans(SpannableStringBuilder spannableStringBuilder, VttContentAttribute vttContentAttribute, int start, int end) {
          // Set font color.
          spannableStringBuilder.setSpan(
              new ForegroundColorSpan(Color.RED),
              start, end,
              Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
          );
          
          // Set absolute size.
          spannableStringBuilder.setSpan(
              new AbsoluteSizeSpan(20), // Unit: px.
              start, end,
              Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
          );
          
          // Set relative size.
          // spannableStringBuilder.setSpan(
          //     new RelativeSizeSpan(2.0f), // Multiple of TextView default font size.
          //     start, end,
          //     Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
          // );
      }
  3. Defina fontes personalizadas (Typeface).

    1. Carregue fontes personalizadas do diretório asset/fonts/.

      private Typeface mTypeface;
      
      public CustomStyleWebVttResolver(Context context) {
          super(context);
          initializeFonts(context);
      }
      
      private void initializeFonts(Context context) {
          try {
              // Load font from assets/fonts/.
              mTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/LongCang.ttf");
          } catch (Exception e) {
              Log.e("Font", "Failed to load font", e);
              mTypeface = Typeface.DEFAULT; // Safe fallback.
          }
      }
    2. Aplique fontes personalizadas às legendas.

      @Override
      protected void applyTextSpans(SpannableStringBuilder builder, VttContentAttribute attr, int start, int end) {
          // Apply custom font.
          // Must be placed after super.applyTextSpans() to override fonts possibly set by the parent class.
          // Calling super.applyTextSpans() is optional.
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
              builder.setSpan(new TypefaceSpan(mTypeface), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
          } else {
              builder.setSpan(new CustomTypefaceSpan(mTypeface), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
          }
      }

      Compatibilidade com versões anteriores do Android: Como o TypefaceSpan no Android P (API 28) e anteriores não suporta passar diretamente um objeto Typeface, você precisa criar um MetricAffectingSpan personalizado.

      /**
        * Custom Typeface Span class.
        * Inherits from MetricAffectingSpan to correctly apply Typeface during text drawing and measurement.
        * Solves the issue where standard TypefaceSpan cannot directly use a Typeface object.
      */
      private static class CustomTypefaceSpan extends MetricAffectingSpan {
      
          // Custom font to apply.
          private final Typeface typeface;
      
          /**
            * Constructor.
            *
            * @param typeface Typeface object to apply (must not be null).
            */
          public CustomTypefaceSpan(Typeface typeface) {
              this.typeface = typeface;
          }
      
          /**
            * Update text drawing state.
            * Called during actual text drawing to set the paint's font.
            *
            * @param tp TextPaint object used for drawing text.
            */
          @Override
          public void updateDrawState(TextPaint tp) {
              tp.setTypeface(typeface);
          }
      
          /**
            * Update text measurement state.
            * Called during text layout calculation (e.g., width, line breaks) to ensure measurement matches actual drawing.
            *
            * @param p TextPaint object used for measuring text.
            */
          @Override
          public void updateMeasureState(TextPaint p) {
              p.setTypeface(typeface);
          }
      }
  4. Integre com o player.

    1. Inicialize a view de legenda.

      // Initialize subtitleView.
      private void initSubtitleView() {
          // Get context.
          Context context = getContext();
      
          // Create CustomStyleWebVttResolver.
          CustomStyleWebVttResolver mResolver = new CustomStyleWebVttResolver(context);
      
          // Create VttSubtitleView and pass CustomStyleWebVttResolver.
          VttSubtitleView mVttSubtitleView = new VttSubtitleView(context, mResolver);
      
          // Add to video container.
          rootView.addView(mVttSubtitleView);
      }
    2. Vincule callbacks de legenda externa.

      // Set subtitle listener.
      mAliPlayer.setOnSubtitleDisplayListener(new IPlayer.OnSubtitleDisplayListener() {
          @Override
          public void onSubtitleExtAdded(int trackIndex, String url) {
              mAliPlayer.selectExtSubtitle(trackIndex, true);
          }
      
          @Override
          public void onSubtitleShow(int trackIndex, long id, String data) {
              if (mVttSubtitleView != null) {
                  // Show subtitle.
                  mVttSubtitleView.show(id, data); 
              }
          }
      
          @Override
          public void onSubtitleHide(int trackIndex, long id) {
              // Hide subtitle.
              mVttSubtitleView.dismiss(id);
          }
      
          @Override
          public void onSubtitleHeader(int i, String header) {
              if (!TextUtils.isEmpty(header)) {
                  // Apply WebVTT header styles.
                  mVttSubtitleView.setVttHeader(header);
              }
          }
      });

Reprodução apenas de áudio

Desative a reprodução de vídeo para obter reprodução apenas de áudio. Configure o PlayerConfig antes de chamar prepare.

PlayerConfig config = aliPlayer.getConfig();
config.mDisableVideo = true;  // Enable audio-only playback.
aliPlayer.setConfig(config);

Alternância entre decodificador de software/hardware

Nota

Altere o método de decodificação antes do início da reprodução. A alteração durante a reprodução não tem efeito.

O Android Player SDK fornece decodificação de hardware H.264 e H.265 com o interruptor enableHardwareDecoder. A decodificação de hardware é ativada por padrão e reverte automaticamente para decodificação de software se a inicialização falhar. Exemplo:

// Enable hardware decoding. Enabled by default.
aliPlayer.enableHardwareDecoder(true);

Se o player alternar automaticamente da decodificação de hardware para software, ele aciona o callback onInfo. Exemplo:

mApsaraPlayerActivity.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if (infoBean.getCode() == InfoCode.SwitchToSoftwareVideoDecoder) {
            // Switched to software decoding.
        }
    }
});

Reprodução adaptativa H.265

Se o dispositivo estiver na lista de bloqueios de decodificação de hardware H.265 baseada em nuvem ou se a decodificação de hardware H.265 falhar, a degradação adaptativa será acionada: se existir um stream de backup H.264, o player o utilizará; caso contrário, haverá degradação para decodificação de software H.265.

Nota
  • Este recurso é ativado somente após você ativar o serviço de valor agregado de decodificação adaptativa integrada cliente-nuvem. Você precisa enviar um formulário Yida para solicitar autorização de licença.

  • O serviço de valor agregado de decodificação adaptativa integrada cliente-nuvem inclui: 1. Entrega dinâmica de dados de compatibilidade de decodificação de hardware baseados em nuvem; 2. Degradação adaptativa de streams H.265 para streams H.264.

  • O SDK ainda possui a capacidade de alternar automaticamente para decodificação de software em caso de falha na decodificação de hardware, mesmo sem ativar o serviço de valor agregado.

    Exemplo de definição de um stream de backup:

// Maintain a Map at the application layer to store key-value pairs of original URLs and backup URLs. When switching, query the backup URL in the Map based on the original URL.
 AliPlayerGlobalSettings.setAdaptiveDecoderGetBackupURLCallback(new AliPlayerGlobalSettings.OnGetBackupUrlCallback() {
    @Override
    public String getBackupUrlCallback(int oriBizScene, int oriCodecType, String original_url) {
        String kurl = original_url;
        if (!H265toH264Map.get(kurl).isEmpty()) {
            return H265toH264Map.get(kurl);
        } else {
            return "";
        }
    }
});

Troca adaptativa de definição de vídeo baseada em rede

Nota
  • Streams de vídeo com bitrate adaptativo HLS podem ser gerados por meio do grupo de modelos de empacotamento e transcodificação de vídeo no ApsaraVideo VOD. Para operações detalhadas, consulte Configurar bitrate adaptativo para VOD.

  • Para streams adaptativos gerados pela transcodificação do ApsaraVideo VOD, se você usar reprodução Vid, deverá especificar a lista de definições de reprodução padrão como DEFINITION_AUTO para obter e reproduzir o stream de vídeo adaptativo. Caso contrário, o player selecionará um stream de vídeo de baixa definição de acordo com a lógica padrão. Para a ordem padrão de reprodução de definições, consulte Qual definição o Player SDK reproduz por padrão quando várias definições são transcodificadas?. Exemplo de especificação da lista de definições para reprodução VidAuth:

    VidAuth vidAuth = new VidAuth();
    List<Definition> list = new ArrayList<>();
    list.add(Definition.DEFINITION_AUTO);
    vidAuth.setDefinition(list);

O Android Player SDK suporta streams de vídeo HLS e DASH com bitrate adaptativo. Após o sucesso de prepare, você pode obter informações sobre cada stream de bitrate, ou seja, TrackInfo, chamando getMediaInfo. Exemplo:

List<TrackInfo> trackInfos  = aliPlayer.getMediaInfo().getTrackInfos();

Durante a reprodução, você pode trocar o stream de bitrate em execução chamando o método selectTrack do player. Quando o valor for AUTO_SELECT_INDEX, a troca adaptativa de bitrate será ativada. Exemplo:

int index = trackInfo.getIndex();
// Switch bitrate.
aliPlayer.selectTrack(index);
// Switch bitrate and enable adaptive switching.
aliPlayer.selectTrack(TrackInfo.AUTO_SELECT_INDEX);

O resultado da troca é retornado por meio do callback OnTrackChangedListener (definido antes de chamar selectTrack). Exemplo:

aliPlayer.setOnTrackChangedListener(new IPlayer.OnTrackChangedListener() {
    @Override
    public void onChangedSuccess(TrackInfo trackInfo) {
        // Switch succeeded.
    }
    @Override
    public void onChangedFail(TrackInfo trackInfo, ErrorInfo errorInfo) {
        // Switch failed. Obtain the failure reason from errorInfo.getMsg().
    }
});

Opcional: Antes de chamar o método selectTrack do player para alternar para bitrate adaptativo, você pode definir o limite superior para troca de bitrate adaptativo (ABR) na configuração para evitar trocas automáticas para bitrates inesperados. Exemplo: (Recomendamos chamar o código abaixo antes que o player chame o método prepare ou antes que o player de playlist chame o método moveTo para que tenha efeito.)

PlayerConfig config = aliPlayer.getConfig();
config.mMaxAllowedAbrVideoPixelNumber = 921600; // Set the pixel count upper limit for ABR definition to 921600 (width × height = 1280 × 720), so ABR allows switching to definitions with pixel counts ≤ this value.
aliPlayer.setConfig(config);

Captura de tela

O Android Player SDK fornece um recurso de captura de tela do vídeo atual, implementado pela interface snapshot. Ele captura os dados originais e os retorna como um bitmap. A interface de callback é OnSnapShotListener. Exemplo:

// Set screenshot callback.
aliPlayer.setOnSnapShotListener(new OnSnapShotListener(){
    @Override
    public void onSnapShot(Bitmap bm, int with, int height){
        // Obtain the bitmap and image dimensions.
    }
});
// Capture the current playback frame.
aliPlayer.snapshot();

Reprodução de prévia

Ao configurar o ApsaraVideo VOD, o Android Player SDK pode implementar reprodução de prévia, suportando os métodos de reprodução VidSts e VidAuth (VidAuth é recomendado para VOD). Para instruções de configuração e uso, consulte Pré-visualizar vídeos.

Após configurar a reprodução de prévia, defina a duração da prévia para o player usando o método VidPlayerConfigGen.setPreviewTime(). Exemplo para reprodução VidSts:

VidSts vidSts = new VidSts;
....
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
configGen.setPreviewTime(20);// 20-second preview.
vidSts.setPlayConfig(configGen);// Set for playback source.
...

Quando a duração da prévia é definida, o servidor retorna apenas o conteúdo dentro do período de prévia, em vez do vídeo completo, ao reproduzir através do Android Player SDK.

Nota

Definir lista de bloqueios

O Android Player SDK fornece um mecanismo de lista de bloqueios de decodificação de hardware. Para dispositivos que explicitamente não podem usar decodificação de hardware, a decodificação de software é usada diretamente para evitar operações ineficazes. Exemplo:

DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.model="Lenovo K320t";
AliPlayerFactory.addBlackDevice(BlackType.HW_Decode_H264 ,deviceInfo );
Nota

A lista de bloqueios é invalidada automaticamente após o encerramento do aplicativo.

Definir Referer

Defina o Referer da solicitação usando PlayerConfig. Combinado com a lista de bloqueios/permissões de Referer no console, isso controla as permissões de acesso. Exemplo:

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Set referer, for example: http://example.aliyundoc.com. (Note: Include the protocol part when setting the referer.)
config.mReferrer = referrer;
....// Other settings.
  // Set configuration for the player.
aliPlayer.setConfig(config);

Definir UserAgent

Defina o UserAgent da solicitação usando PlayerConfig. O player inclui o UA nas solicitações. Exemplo:

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Set UA.
config.mUserAgent = "UserAgent to set";
....// Other settings.
  // Set configuration for the player.
aliPlayer.setConfig(config);

Configurar tempo e contagem de tentativas de rede

Defina o tempo limite de rede e a contagem de tentativas usando PlayerConfig. Exemplo:

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Set network timeout duration, in milliseconds.
config.mNetworkTimeout = 5000;
// Set timeout retry count. The interval between retries is networkTimeout. networkRetryCount=0 means no retry; the retry policy is determined by the app. Default value is 2.
config.mNetworkRetryCount=2;
....// Other settings.
  // Set configuration for the player.
aliPlayer.setConfig(config);
Nota
  • Se NetworkRetryCount estiver definido e um problema de rede causar carregamento, o player tentará novamente NetworkRetryCount vezes, sendo cada intervalo igual a mNetworkTimeout.

  • Se o status de carregamento persistir após várias tentativas, o evento onError será acionado, com ErrorInfo.getCode()=ErrorCode.ERROR_LOADING_TIMEOUT.

  • Se NetworkRetryCount estiver definido como 0, quando o tempo limite de tentativa de rede expirar, o player acionará o evento onInfo, com InfoBean.getCode()=InfoCode.NetworkRetry. Nesse ponto, você pode chamar o método reload do player para recarregar a rede ou lidar com a situação de outra forma.

Configurar cache e controle de latência

O Android Player SDK fornece interfaces para controlar cache e latência através de PlayerConfig. Exemplo:

Expandir para visualizar o código

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Maximum latency. Note: Valid for live streaming. When latency is large, the player SDK internally synchronizes frames to keep latency within this range.
config.mMaxDelayTime = 5000;
// Maximum buffer duration, in ms. The player loads up to this duration of buffer data each time.
config.mMaxBufferDuration = 50000;
// High buffer duration, in ms. When poor network conditions cause data loading, loading stops when buffer duration reaches this value.
config.mHighBufferDuration = 3000;
// Startup buffer duration, in ms. Shorter duration means faster startup but may cause quick entry into loading state after playback starts.
config.mStartBufferDuration = 500;
....// Other settings.
// Maximum backward buffer duration, in ms. Default is 0.
config.mMaxBackwardBufferDurationMs = 0;

// Set configuration for the player.
aliPlayer.setConfig(config);
Importante
  • As durações de buffer devem satisfazer: mStartBufferDuration ≤ mHighBufferDuration ≤ mMaxBufferDuration.

  • Se mMaxBufferDuration exceder 5 minutos, o sistema usará o padrão de 5 minutos para evitar exceções de memória causadas por tamanho excessivo de buffer.

Definir cabeçalhos HTTP

Usando o método PlayerConfig, você pode adicionar parâmetros de cabeçalho HTTP às solicitações no player. Exemplo:

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Define headers.
String[] headers = new String[1];
headers[0]="Host:example.com";// For example, set Host in the header.
// Set headers.
config.setCustomHeaders(headers);
....// Other settings.
  // Set configuration for the player.
aliPlayer.setConfig(config);

Picture-in-Picture

Nota

Para exemplos de código detalhados, consulte o módulo API-Example Reprodução Picture-in-Picture (PictureInPicture). Este projeto de exemplo baseado em Java para o ApsaraVideo Player SDK para Android ajuda os desenvolvedores a dominar rapidamente os principais recursos de integração do SDK.

Procedimento:

  1. No arquivo AndroidManifest.xml, declare as permissões de Picture-in-Picture.

    <activity
      android:name=".PictureInPictureActivity"
      android:exported="true"
      android:supportsPictureInPicture="true"
      android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation" />
  2. Alterne a Activity alvo para o modo Picture-in-Picture.

    Rational aspectRatio = new Rational(16, 9); // Aspect ratio for Picture-in-Picture; adjust based on your business needs.
    PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder();
    pipBuilder.setAspectRatio(aspectRatio);
    enterPictureInPictureMode(pipBuilder.build());

    Você pode acionar o modo Picture-in-Picture a partir de OnClick (evento de clique), ao sair do aplicativo ou ao retornar ao aplicativo. Métodos de implementação:

    Acionador OnClick (evento de clique)

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Rational aspectRatio = new Rational(16, 9); // Aspect ratio for Picture-in-Picture.
            PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder();
            pipBuilder.setAspectRatio(aspectRatio);
            enterPictureInPictureMode(pipBuilder.build());
        }
    });

    Acionar ao sair do aplicativo

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        Rational aspectRatio = new Rational(16, 9); // Aspect ratio for Picture-in-Picture.
        PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder();
        pipBuilder.setAspectRatio(aspectRatio);
        enterPictureInPictureMode(pipBuilder.build());
    
        Log.e(TAG, "Picture-in-Picture onUserLeaveHint");
    }

    Acionar ao retornar ao aplicativo

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // Trigger from back press.
        enterPictureInPictureMode();
    }
  3. Gerencie a UI para exibição/desaparecimento do Picture-in-Picture.

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        if (isInPictureInPictureMode) {
            // Handle entering Picture-in-Picture mode.
            // hide UI
            Log.e(TAG, "Entered Picture-in-Picture mode");
        } else {
            // Handle exiting Picture-in-Picture mode.
            // show UI 
            Log.e(TAG, "Exited Picture-in-Picture mode");
        }
    }

Degradação RTS ao vivo

Nota

Para exemplos de código detalhados, consulte o módulo API-Example Reprodução ao vivo RTS de latência ultrabaixa (RtsLiveStream). Este projeto de exemplo baseado em Java para o ApsaraVideo Player SDK para Android ajuda os desenvolvedores a dominar rapidamente os principais recursos de integração do SDK.

Reprodução ao vivo RTS.

Alternar canais de áudio esquerdo/direito

O Android Player SDK fornece o método setOutputAudioChannel para definir o canal de saída de áudio. Se a fonte de entrada for estéreo, você pode alternar para o canal esquerdo ou direito usando este método. Se a fonte de entrada for mono, a configuração não terá efeito.

Nota

A configuração do canal de saída de áudio afeta tanto a renderização de áudio quanto os callbacks de dados PCM.

/*
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_LEFT switches to left channel playback,
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_RIGHT switches to right channel playback,
OutputAudioChannel.OUTPUT_AUDIO_CHANNEL_NONE does not switch channels, maintaining the input source channels.
*/
aliPlayer.setOutputAudioChannel();

Analisar streams de áudio

Defina um listener para obter dados de streams de áudio e vídeo. Os streams não devem estar criptografados, pois streams criptografados não podem ser analisados.

Expandir para visualizar o código

// Optional configuration 1: Whether to return the address of underlying data.
IPlayer.RenderFrameCallbackConfig config = new IPlayer.RenderFrameCallbackConfig();
config.mVideoDataAddr = true;// Whether to return only the address of underlying video data.
config.mAudioDataAddr = true;// Whether to return only the address of underlying audio data.
aliPlayer.setRenderFrameCallbackConfig(config);

// Optional configuration 2: For hardware decoding, RenderFrame returns texture_oes_id; for software decoding, RenderFrame returns source data.
aliPlayer.enableHardwareDecoder(true);
// Set listener to obtain audio and video data.
aliPlayer.setOnRenderFrameCallback(frameInfo -> {
    if (frameInfo.frameType == FrameInfo.FrameType_video) {
        // Video data.
    } else {
        // Audio data.
    }
    return false;
});

Definir cor de fundo do vídeo

O Android Player SDK suporta a definição da cor de fundo para a renderização do player. Interface e instruções de uso:

Exemplo de interface

/**
 * Set video background color.
 *
 * @param color  ARGB
 */
abstract public void setVideoBackgroundColor(int color);

Instruções de uso

// Parameter is an 8-digit hexadecimal value. Each pair of digits represents A (alpha transparency), R (red), G (green), B (blue) in order.
// For example, 0x0000ff00 represents green.
aliPlayer.setVideoBackgroundColor(0x0000ff00);

vidAuthDefinir domínio de reprodução especificado

Usando vidAuth, você pode especificar campos como o domínio para o vid. Para campos suportados, consulte Parâmetros de solicitação GetPlayInfo. Interface e instruções de uso:

Exemplo de interface

/**
 * Set playback parameters.
 *
 * @param playConfig Playback parameters.
 */
public void setPlayConfig(VidPlayerConfigGen playConfig);

Instruções de uso

Use o método addPlayerConfig de VidPlayerConfigGen para adicionar o campo playDomain.

vidAuth = new VidAuth();
VidPlayerConfigGen configGen = new VidPlayerConfigGen();
// Add playDomain field. For other fields you can add, refer to
//https://www.alibabacloud.com/help/zh/vod/developer-reference/api-vod-2017-03-21-getplayinfo
configGen.addPlayerConfig("playDomain", "com.xxx.xxx");
vidAuth.setPlayConfig(configGen);

Plugin de decodificação H.266

O H.266 (VVC/Versatile Video Coding) é um padrão de codificação de vídeo de próxima geração que reduz significativamente a taxa de bits com qualidade equivalente. A capacidade de decodificação H.266 é empacotada independentemente como um plugin para integração sob demanda.

Pré-requisitos

  1. Versão do Player/Integrated SDK V7.6.0 ou posterior.

  2. Autorização de licença da Professional Edition concluída. Obter uma licença do Player SDK.

  3. O ApsaraVideo Player com o plugin de decodificação H.266 suporta apenas vídeos H.266 transcodificados pelo ApsaraVideo VOD transcodificação de áudio e vídeo.

Integrar plugin

Player SDK

Integração Maven (recomendada)

Adicione a dependência para a versão especificada do plugin no arquivo build.gradle do seu aplicativo:

Nota

Para as versões mais recentes do Android Player SDK, consulte Histórico de lançamentos do Android SDK.

// x.x.x matches the player SDK version number.
com.aliyun.sdk.android:AlivcVVCCodec:x.x.x

Integração local

Baixe o Android Player SDK mais recente e copie o pacote AlivcVVCCodec para o diretório libs do seu projeto (crie-o manualmente se não existir). Para detalhes, consulte Integração local.

Integrated SDK

Integração Maven

Adicione a dependência para a versão especificada do plugin no arquivo build.gradle do seu aplicativo:

// x.x.x matches the integrated SDK version number.
com.aliyun.sdk.android:AlivcVVCCodec:x.x.x-aio

Ativar plugin

Nota

A partir do Android Player SDK 7.7.0, o plugin é ativado por padrão após a integração e não requer ativação manual.

AliPlayerGlobalSettings.enableCodecPlugin("vvc", true);

Códigos de erro relacionados

Para códigos de erro do plugin de decodificação H.266, consulte Problemas comuns para players em todas as plataformas.

Atualização automática de fontes de reprodução

Ativar a atualização automática para fontes de reprodução evita interrupções na reprodução causadas pela expiração da fonte sob mecanismos de autenticação.

Pré-requisitos

  1. Versão do Player/Integrated SDK V7.9.0 ou posterior.

  2. Uso de fonte VidAuth para reprodução ou seu negócio tem assinatura de URL configurada.

Fonte VidAuth

Exemplo de interface

/**
 * Set the listener for VidAuth source expiration events.
 *
 * This feature enables automated VidAuth source refresh to avoid playback interruptions
 * caused by expiration. When the listener is triggered, you can refresh the VidAuth source
 * and return the updated VidAuth using {@link SourceRefreshCallback#onSuccess}.
 *
 * @param listener The interface for listening to VidAuth source expiration events. See {@link OnVidAuthExpiredListener}.
 */
abstract public void setOnVidAuthExpiredListener(OnVidAuthExpiredListener listener);

Componentes do recurso

Componentes do recurso

/**
 * Listener for VidAuth source expiration notifications.
 * Handles events when a VidAuth source expires.
 */
public interface OnVidAuthExpiredListener {

    /**
     * Called when the player detects that the VidAuth source has expired.
     *
     * You can refresh the VidAuth source in this callback and return the new VidAuth
     * using {@link SourceRefreshCallback#onSuccess}.
     *
     * @param expiredSource The expired VidAuth source object. See {@link VidAuth}.
     * @param callback The callback used to provide the updated VidAuth source to the player. See {@link SourceRefreshCallback}.
     */
    void onVidAuthExpired(VidAuth expiredSource, SourceRefreshCallback<VidAuth> callback);
}

/**
 * A callback interface for handling playback source refresh results.
 *
 * This interface is applicable to playback source types that require dynamic updates,
 * such as URL source or VidAuth source. When the player triggers a refresh request,
 * the refresh result can be returned via this interface by invoking either the `onSuccess` or `onError` method.
 */
public interface SourceRefreshCallback<T extends SourceBase> {
    /**
     * Called by the player when the refresh operation succeeds.
     *
     * @param newSource The new playback source object containing the updated information. See {@link SourceBase}.
     *
     * This method indicates that the refresh operation was successfully completed. Developers should provide
     * the new playback source within this method so that the player can load the latest resource.
     */
    void onSuccess(T newSource);

    /**
     * Called by the player when the refresh operation fails.
     *
     * @param errorMsg A string describing the reason for the failure.
     *
     * This method indicates that the refresh operation has failed. Developers can use the `errorMsg`
     * to capture details of the failure and proceed with subsequent handling.
     */
    void onError(String errorMsg);
}

Instruções de uso

Obtenha credenciais de reprodução de vídeo usando a API GetVideoPlayAuth. Recomendamos integrar o VOD server SDK para obter credenciais e evitar a autoassinatura. Para mais informações, consulte Portal OpenAPI.

// Set VID playback credential expiration listener.
aliPlayer.setOnVidAuthExpiredListener(new AliPlayer.OnVidAuthExpiredListener() {
    @Override
    public void onVidAuthExpired(VidAuth vidAuth, UrlPlayer.SourceRefreshCallback<VidAuth> sourceRefreshCallback) {
        
        String vid = vidAuth.getVid();

        // ------------------- User implementation starts -------------------
        // Call your own function to get new PlayAuth from your app server.
        // clinetGetPlayAuthFunction is an example function name; replace it with your own implementation.
        clinetGetPlayAuthFunction(vid, new PlayAuthCallback() {
            
            /**
             * Callback when new credentials are successfully obtained.
             * @param newPlayAuth New playback credential string obtained from your server.
             */
            @Override
            public void onAuthSuccess(String newPlayAuth) {                
                // 1. Update the old vidAuth object with the new PlayAuth.
                vidAuth.setPlayAuth(newPlayAuth);
                
                // 2. Return the updated object to the player via the SDK callback.
                sourceRefreshCallback.onSuccess(vidAuth);
            }

            /**
             * Callback when obtaining new credentials fails.
             * @param errorMessage Detailed error message.
             */
            @Override
            public void onAuthError(String errorMessage) {                
                // Return the error message to the player via the SDK callback.
                sourceRefreshCallback.onError(errorMessage);
            }
        });
        // ------------------- User implementation ends -------------------
    }
});

Fonte UrlSource

Exemplo de interface

/**
 * Set the listener for URL source expiration events.
 *
 * This feature enables URL refresh to avoid playback interruptions caused by
 * URL expiration due to authentication. When the listener is triggered,
 * you can refresh the URL source and return the updated URL source using {@link SourceRefreshCallback#onSuccess}.
 *
 * @param listener Listener for handling URL source expiration events. See {@link OnURLSourceExpiredListener}.
 *
 * <p>For more information on configuring URL authentication, see
 * <a href="https://www.alibabacloud.com/help/zh/vod/user-guide/configure-url-signing?spm=a2c4g.11186623.0.0.560c4140fGh8MW">URL authentication documentation</a>.</p>
 */
abstract public void setOnURLSourceExpiredListener(OnURLSourceExpiredListener listener);

Componentes do recurso

Componentes do recurso

/**
 * A callback interface for handling playback source refresh results.
 *
 * This interface is applicable to playback source types that require dynamic updates,
 * such as URL source or VidAuth source. When the player triggers a refresh request,
 * the refresh result can be returned via this interface by invoking either the `onSuccess` or `onError` method.
 */
public interface SourceRefreshCallback<T extends SourceBase> {
    /**
     * Called by the player when the refresh operation succeeds.
     *
     * @param newSource The new playback source object containing the updated information. See {@link SourceBase}.
     *
     * This method indicates that the refresh operation was successfully completed. Developers should provide
     * the new playback source within this method so that the player can load the latest resource.
     */
    void onSuccess(T newSource);

    /**
     * Called by the player when the refresh operation fails.
     *
     * @param errorMsg A string describing the reason for the failure.
     *
     * This method indicates that the refresh operation has failed. Developers can use the `errorMsg`
     * to capture details of the failure and proceed with subsequent handling.
     */
    void onError(String errorMsg);
}

/**
 * Listener for URL source expiration notifications.
 * This helps process expired sources and prevents playback interruptions.
 */
public interface OnURLSourceExpiredListener {

    /**
     * Called when the player detects that the URL source (UrlSource) has expired.
     *
     * You can refresh the URL source in this callback and return the new UrlSource
     * using {@link SourceRefreshCallback#onSuccess}.
     *
     * @param expiredSource The expired UrlSource object. See {@link UrlSource}.
     * @param callback The refresh callback used to return the updated UrlSource to the player. See {@link SourceRefreshCallback}.
     */
    void onUrlSourceExpired(UrlSource expiredSource, SourceRefreshCallback<UrlSource> callback);
}

Instruções de uso

// Set the player's URL expiration listener.
mAliyunVodPlayer.setOnURLSourceExpiredListener(new UrlPlayer.OnURLSourceExpiredListener() {
    @Override
    public void onUrlSourceExpired(UrlSource urlSource, UrlPlayer.SourceRefreshCallback<UrlSource> sourceRefreshCallback) {
        String expiredUrl = urlSource.getUri();
        Log.d(TAG, "[onUrlSourceExpired] Received expired URL: " + expiredUrl);

        // 1. Check if the authentication key is valid (assuming authenticationKey is a member variable of the class).
        if (authenticationKey == null || authenticationKey.trim().isEmpty()) {
            Log.e(TAG, "Refresh failed: Authentication key is empty.");
            sourceRefreshCallback.onError("REFRESH_ERROR: Authentication key is missing.");
            return; // Exit early if the key is invalid.
        }

        // 2. Calculate the validity duration (expiration time) for the playback URL.
        // If the class member validTime is valid, use it; otherwise, default to 3600 seconds (1 hour).
        long validityDuration = (AliyunVodPlayerView.this.validTime > 0) ? validTime : 3600;
        long newExpireTime = (System.currentTimeMillis() / 1000) + validityDuration;

        // 3. Extract the original URL from the expired URL (using authentication type A as an example).
        // Restore the original resource address by removing URL parameters (e.g., "?auth_key=").
        int authKeyIndex = expiredUrl.indexOf("?auth_key=");
        if (authKeyIndex == -1) {
            authKeyIndex = expiredUrl.indexOf("&auth_key=");
        }
        // Safely handle cases where auth_key is not found.
        String originalUrl = (authKeyIndex != -1) ? expiredUrl.substring(0, authKeyIndex) : expiredUrl;

        // 4. Generate a new authenticated URL using a utility class.
        String newAuthUrl = CdnAuthUtil.aAuth(originalUrl, authenticationKey, newExpireTime);

        // 5. Check the generated authenticated URL and return the result via callback.
        if (newAuthUrl != null && !newAuthUrl.isEmpty()) {
            Log.i(TAG, "Refresh success, new URL: " + newAuthUrl);
            // Create a UrlSource object as required by the SDK and set the new URL.
            UrlSource resultSource = new UrlSource();
            resultSource.setUri(newAuthUrl);
            sourceRefreshCallback.onSuccess(resultSource);
        } else {
            Log.e(TAG, "Refresh failed: Failed to generate new authorized URL.");
            sourceRefreshCallback.onError("REFRESH_ERROR: Failed to generate new URL.");
        }
    }
});

Funções utilitárias suplementares

Usando tipo de autenticação A como exemplo.

Funções utilitárias suplementares

// Authenticated URL generation function.
private String generateAuthUrl(String uri, String key, long exp) {
    Pattern uriPattern = Pattern.compile("^(https?://)?([^/?]+)(/[^?]*)?(\\?.*)?$");
    Matcher m = uriPattern.matcher(uri);

    if (!m.matches()) {
        return null;
    }

    String scheme = (m.group(1) != null) ? m.group(1) : "http://";
    String host = m.group(2);
    String path = (m.group(3) != null) ? m.group(3) : "/";
    String args = (m.group(4) != null) ? m.group(4) : "";

    String rand = "0";
    String uid = "0";

    String sstring = String.format("%s-%d-%s-%s-%s", path, exp, rand, uid, key);
    String hashvalue = md5sum(sstring);
    String authKey = String.format("%d-%s-%s-%s", exp, rand, uid, hashvalue);

    if (!args.isEmpty()) {
        return String.format("%s%s%s%s&auth_key=%s", scheme, host, path, args, authKey);
    } else {
        return String.format("%s%s%s%s?auth_key=%s", scheme, host, path, args, authKey);
    }
}

// MD5 calculation utility function.
private String md5sum(String src) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(src.getBytes(StandardCharsets.UTF_8));
        byte[] digest = md.digest();

        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 algorithm not found", e);
    }
}

Alternar NIC vinculada

O Android Player SDK fornece o método AliPlayerGlobalSettings.enableSwitchNIC para alternar automaticamente NICs durante anomalias de rede, garantindo reprodução estável de recursos. Exemplo:

Nota

Isso só entra em vigor quando o interruptor está ativado e existem múltiplas NICs.

AliPlayerGlobalSettings.enableSwitchNIC(true);

Aprimoramento de áudio

O Android Player SDK fornece um plugin de aprimoramento de áudio para melhorar a experiência de reprodução de áudio, apresentando normalização de volume, aprimoramento de voz e som surround.

Introdução ao recurso

  • Normalização de volume: Ajusta automaticamente todo o conteúdo de áudio para um nível de volume consistente, melhorando significativamente a experiência de reprodução para vídeos com volume original excessivamente baixo ou alto.

    • Canais suportados: Mono / Estéreo / 5,1 / 7,1.

    • Taxas de amostragem suportadas: 16kHz / 44,1kHz / 48kHz.

  • Aprimoramento de voz: Aprimora inteligentemente o diálogo preservando o timbre original, tornando as vozes mais claras e brilhantes em cenas ruidosas.

    • Canais suportados: Estéreo.

    • Taxas de amostragem suportadas: 44,1kHz / 48kHz.

  • Som surround: Aplica renderização de surround virtual a vídeos multicanal e estéreo, proporcionando uma experiência imersiva em fones de ouvido ou dispositivos padrão. Inclui os modos 3DSurround (surround estéreo) e MegaBass (super graves).

    • Canais suportados: Mono / Estéreo / 5,1 / 7,1.

    • Taxas de amostragem suportadas: 44,1kHz / 48kHz.

Pré-requisitos

  1. Versão do Player/Integrated SDK V7.13.0 ou posterior.

  2. Autorização de Licença da Professional Edition obtida. Obter uma licença do Player SDK.

Importante

Suporte de fonte de áudio para aprimoramento de áudio:

Integrar plugin

Integração Maven (recomendada)

Adicione a dependência para a versão especificada do plugin no arquivo build.gradle do seu aplicativo:

Nota

Para as versões mais recentes do Android Player SDK, consulte Histórico de lançamentos do Android SDK.

// x.x.x matches the player SDK version number.
implementation 'com.aliyun.sdk.android:AlivcAudioEnhanceFilter:x.x.x'

Integração local

Baixe o Android Player SDK mais recente e copie o pacote AlivcAudioEnhanceFilter para o diretório libs do seu projeto (crie-o manualmente se não existir). Para detalhes, consulte Integração local.

Interfaces do recurso

setFilterValid

Controla o interruptor principal para aprimoramento de áudio. O nome target para o filtro de aprimoramento de áudio é audioEnhance. Quando desativado, todos os três sub-recursos ficam inativos (desativado por padrão).

player.setFilterValid("audioEnhance", true);   // Enable.
player.setFilterValid("audioEnhance", false);  // Disable.
setFilterConfig

Defina FilterConfig antes de prepare. Entra em vigor após o início da reprodução.

FilterConfig filterConfig = new FilterConfig();
FilterConfig.Filter filterItem = new FilterConfig.Filter("audioEnhance");
FilterConfig.FilterOptions opts = new FilterConfig.FilterOptions();
// Surround sound.
opts.setOption("enable_surround", true);
opts.setOption("surround_effect_type", "3DSurround"); // Type must be set together with enable_surround on first use.
// Voice enhancement.
opts.setOption("enable_dialoguenhance", true);
opts.setOption("dialoguenhance_voice", 1.0f); // 1.0 ~ 10.0. Voice must be set together with enable_dialoguenhance on first use.
// Volume normalization.
opts.setOption("enable_normalizer", true);

filterItem.setOptions(opts);
filterConfig.addFilter(filterItem);
player.setFilterConfig(filterConfig);

Parâmetro

Tipo

Descrição

enable_surround

Boolean

Interruptor do recurso de som surround.

surround_effect_type

String

Tipo de som surround: "3DSurround" / "MegaBass".

enable_dialoguenhance

Boolean

Interruptor do recurso de aprimoramento de voz.

dialoguenhance_voice

Float

Intensidade do aprimoramento de voz, faixa 1,0 ~ 10,0.

enable_normalizer

Boolean

Interruptor do recurso de normalização de volume.

updateFilterConfig

Durante ou após a preparação do player, para ajustar parâmetros dinamicamente, chame esta interface para atualizá-los.

Nota

Chamar updateFilterConfig antes de prepare não tem efeito. Use setFilterConfig para a configuração inicial.

AVPFilterOptions *opts = [[AVPFilterOptions alloc] init];
[opts setOptions:@"enable_surround" value:@YES];
[opts setOptions:@"surround_effect_type" value:@"3DSurround"]; // If not the first time enabling surround, this Type setting is invalid because initialization is already complete.
[player updateFilterConfig:@"audioEnhance" options:opts];
Importante

O tipo de som surround ("3DSurround" / "MegaBass") e a intensidade do aprimoramento de voz (dialoguenhance_voice) devem ser definidos juntamente com o atributo enable no primeiro uso. Caso contrário, valores padrão serão usados para inicialização (som surround padrão é "3DSurround", intensidade de voz padrão é 1,0), e eles não poderão ser modificados durante a reprodução.

Desempenho

Definir cenário de reprodução

Definir o cenário de reprodução configura automaticamente parâmetros ideais (incluindo configurações de buffer e interruptores de recursos). É compatível com configurações de parâmetros personalizados via interface setConfig (configurações personalizadas têm precedência).

Nota
  • Após definir o cenário de reprodução, você pode visualizar a configuração de parâmetros usando a interface getConfig.

Exemplo de interface

/**
 * Set the player scenario.
 *
 * @param scene 
 */
abstract public void setPlayerScene(PlayerScene scene);

Cenários de reprodução

public enum PlayerScene {
    /**
     * Scenario: none.
     */
    NONE,
    /**
     * Long video scenario: applies to videos longer than 30 minutes.
     */
    LONG,
    /**
     * Medium video scenario: applies to videos between 5 and 30 minutes.
     */
    MEDIUM,
    /**
     * Short video scenario: applies to videos up to 5 minutes.
     */
    SHORT,
    /**
     * Live scenario.
     */
    LIVE,
    /**
     * Ultra-low latency live scenario.
     */
    RTS_LIVE
}

Instruções de uso

// Set short video scenario.
aliPlayer.setPlayerScene(PlayerScene.SHORT)

// Set medium video scenario.
aliPlayer.setPlayerScene(PlayerScene.MEDIUM)

// Set long video scenario.
aliPlayer.setPlayerScene(PlayerScene.LONG)

// Set live scenario.
aliPlayer.setPlayerScene(PlayerScene.LIVE)

Pré-renderização

O Android Player SDK suporta renderizar rapidamente o primeiro quadro antes do início da reprodução, o que pode melhorar a velocidade de inicialização.

Nota
  1. Este recurso é desativado por padrão.

  2. Você deve definir a View antes de chamar Prepare para garantir que o quadro seja renderizado na View assim que estiver pronto.

  3. Ativar este recurso afeta a ordem de acionamento dos eventos de sucesso de preparação e renderização do primeiro quadro: sem ele, o sucesso de preparação é acionado antes da renderização do primeiro quadro; com ele, devido a diferenças na velocidade de decodificação e renderização, a renderização do primeiro quadro pode ser acionada antes do sucesso de preparação, mas isso não afeta a reprodução.

    Exemplo:

aliPlayer.setOption(ALLOW_PRE_RENDER, 1);

Cache local

Nota

Para exemplos de código detalhados, consulte o módulo API-Example Pré-carregamento de vídeo (Preload). Este projeto de exemplo baseado em Java para o ApsaraVideo Player SDK para Android ajuda os desenvolvedores a dominar rapidamente os principais recursos de integração do SDK.

O cache local melhora a velocidade de início, a velocidade de busca e reduz travamentos para reprodução repetida, economizando largura de banda.

Ativar cache local

O cache local é desativado por padrão. Para usá-lo, ative-o manualmente usando AliPlayerGlobalSettings e enableLocalCache. Exemplo:

Expandir para visualizar o código

// Enable local cache (default path).
AliPlayerGlobalSettings.enableLocalCache(true, this);

/**
 * You can also use the following code for cache settings.
 * Enable local cache. After enabling, content is cached to local files.
 * @param enable: Local cache feature switch. true: enable, false: disable. Disabled by default.
 * @param maxBufferMemoryKB: Deprecated since version 5.4.7.1, currently has no effect.
 * @param localCacheDir: Must be set. Local cache directory as an absolute path.
 * AliPlayerGlobalSettings.enableLocalCache(enable, maxBufferMemoryKB, localCacheDir);
 */

/**
 * Local cache file cleanup configuration.
 * @param expireMin - Deprecated since version 5.4.7.1, currently has no effect.
 * @param maxCapacityMB - Maximum cache capacity in MB. Default is 20 GB. During cleanup, if total cache size exceeds this value, cache items are deleted one by one from oldest to newest until size is ≤ maxCapacityMB.
 * @param freeStorageMB - Minimum free disk space in MB. Default is 0. During cleanup, if current disk space is less than this value, cache items are deleted one by one until free space ≥ this value or all cache is cleared.
 * public static void setCacheFileClearConfig(long expireMin,
 *         long maxCapacityMB,
 *         long freeStorageMB)
 */

 /**
  * Set callback for loading URL hash value. If not set, SDK uses MD5 algorithm.
  * public static void setCacheUrlHashCallback(AliPlayerGlobalSettings.OnGetUrlHashCallback cb)
  */
Nota
  • Se as URLs de reprodução de vídeo incluírem parâmetros de autenticação, os parâmetros mudarão entre o cache e a reprodução. Para melhorar a taxa de acerto de cache para a mesma URL sob diferentes autenticações, remova os parâmetros de autenticação antes de calcular o valor hash (por exemplo, MD5) via setCacheUrlHashCallback. Por exemplo, para uma URL como http://****.mp4?aaa, calcule o hash usando http://****.mp4. No entanto, para vídeos m3u8 criptografados, se você remover parâmetros de autenticação das keyURLs antes do hashing, vídeos diferentes podem atingir a mesma chave, causando falha na reprodução. Solução: No callback setCacheUrlHashCallback, verifique o domínio e remova os parâmetros de autenticação apenas para domínios de reprodução (http(s)://xxxxx.m3u8?aaaa), não para domínios keyURL (http(s)://yyyyy?bbbb). Use curl para obter a playlist de vídeo criptografado HLS M3U8, onde playURL é o endereço M3U8 e keyURL é o endereço da chave de descriptografia AES-128. Exemplo de saída do terminal:

    # playURL: M3U8 playlist request
    C:\Users\futan>curl "https://videxxxv.cc/a003xxx2a-hd-encrypt-stream.m3u8?MtsHlsUriToken=uheAz07oi-jlo9CeIU6LxxxAr4a3WtzrJXnCn4ClS44dTYHCQGmXBlo7TyuPLE0a&auth_key=17xxxrmonwFHJ"
    
    #EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-ALLOW-CACHE:YES
    #EXT-X-TARGETDURATION:10
    #EXT-X-MEDIA-SEQUENCE:0
    # keyURL: AES-128 encryption key address
    #EXT-X-KEY:METHOD=AES-128,URI="https://apxxx.cc/decrypt?Ciphertext=NWNiNDQyN2MtNjV1ZS00ZWIwLTk0YTAtNTJhOWIyZWV1OTY2MzdoRTJ6TjVxcXkweFY2xxxNCt4OGNFRGNReHRG&MtsHlsUriToken=uheAz07oi-jlo9CeIU6LxxxAr4a3WtzrJXnCn4ClS44dTYHCQGmXBlo7TyuPLE0a"
    #EXTINF:10.000000,
    e9012989ecd8e987eb7349d84d3b06d8-hd-encrypt-stream-00001.ts?auth_key=1706560316-65b7xxx39f1d6c77
    #EXTINF:10.000000,
    e9012989ecd8e987eb7349d84d3b06d8-hd-encrypt-stream-00002.ts?auth_key=1706560316-65b7xxxe8eca2faf
    #EXTINF:10.000000,
    e9012989ecd8e987eb7349d84d3b06d8-hd-encrypt-stream-00003.ts?auth_key=1706560316-65b7xxx50c6981b3
    #EXTINF:10.000000,
    e9012989ecd8e987eb7349d84d3b06d8-hd-encrypt-stream-00004.ts?auth_key=1706560316-65b7xxxf7228c594
    #EXTINF:10.000000,
    e9012989ecd8e987eb7349d84d3b06d8-hd-encrypt-stream-00005.ts?auth_key=1706560316-65b7xxx6dc68c35d
  • Se o servidor suportar protocolos HTTP e HTTPS apontando para o mesmo arquivo de mídia, remova ou padronize o protocolo antes de calcular o hash. Por exemplo:

    • Para URLs https://****.mp4 e http://****.mp4, calcule o hash usando ****.mp4.

    • Para a URL https://****.mp4, padronize para http://****.mp4 antes de calcular o hash.

  • Para a versão 5.5.4.0 ou posterior do Player SDK, se a URL de reprodução de vídeo incluir parâmetros de autenticação e usar o protocolo HLS, você pode definir PlayerConfig.mEnableStrictAuthMode para escolher entre os modos de autenticação (o padrão é false para versões mais antigas; true para a versão 7.13.0 e posteriores):

    • Autenticação não estrita (false): A autenticação é armazenada em cache. Se apenas parte da mídia foi armazenada em cache anteriormente, o player usa a autenticação em cache para solicitações subsequentes. Se a autenticação de URL tiver um curto período de validade ou a reprodução for retomada após uma longa pausa, a autenticação pode expirar. Integre com atualização automática de fontes de reprodução para lidar com a expiração da autenticação.

    • Autenticação estrita (true): A autenticação não é armazenada em cache. A autenticação ocorre em cada inicialização, causando falha na inicialização sem rede.

Ativar ou desativar cache local para uma única URL

Para ativar ou desativar o cache local para uma URL específica, defina-o na player config.

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Whether to enable local cache for the playback URL. Default is true. When global local cache is enabled and this is set to true, local cache takes effect for this URL. If set to false, local cache is disabled for this URL.
config.mEnableLocalCache = false;
....// Other settings.

// Set configuration for the player.
aliPlayer.setConfig(config);

Cache grande

Definir a duração máxima do buffer armazena dados de vídeo na memória durante a reprodução, melhorando o desempenho e a experiência de visualização. No entanto, grandes durações de buffer consomem memória significativa. Ativar o cache grande armazena dados de vídeo em arquivos, reduzindo o uso de memória e melhorando ainda mais o desempenho do player.

Quando mMaxBufferDuration excede 50000 ms, ativar o cache local ativa automaticamente o cache grande. Procedimento:

  1. Ative o cache local global.

    O cache local é desativado por padrão. Para usá-lo, ative-o manualmente usando AliPlayerGlobalSettings e enableLocalCache. Para exemplos de código, consulte Cache local em Ativar cache local.

  2. Ative o cache local para a URL.

    Para exemplos de código, consulte Cache local em Ativar ou desativar cache local para uma única URL.

  3. Ative o cache grande.

    AliPlayerGlobalSettings.enableBufferToLocalCache(true);

Pré-carregamento

O pré-carregamento é uma evolução do cache local que melhora a velocidade de início do vídeo definindo o uso de memória para armazenamento de vídeo em cache.

Limitações do pré-carregamento:

  • Atualmente suporta o carregamento de arquivos de mídia únicos, como MP4, MP3, FLV e HLS.

Nota

O Android Player SDK fornece agendamento automático de recursos de rede durante o pré-carregamento por padrão para reduzir o impacto das solicitações de rede de pré-carregamento na reprodução de vídeo em andamento. A estratégia de agendamento automático permite solicitações de pré-carregamento somente depois que o buffer do vídeo atualmente em reprodução atinge um determinado limiar. Para controlar as solicitações de pré-carregamento em tempo real você mesmo, desative essa estratégia usando o seguinte método:

AliPlayerGlobalSettings.enableNetworkBalance(false);
  1. Ative o cache local. Para etapas detalhadas, consulte Cache local.

  2. Defina a fonte de dados.

    VidAuth (recomendado)

    VidAuth vidAuth = new VidAuth();
    vidAuth.setVid("Vid info");// Required parameter: Video ID.
    vidAuth.setPlayAuth("<yourPlayAuth>");// Required parameter: Playback credential, generated by calling the GetVideoPlayAuth API of VOD.
    vidAuth.setRegion("Access region");// For player SDK version 5.5.5.0 and later, this parameter is deprecated and not required; the player automatically parses the region. For versions before 5.5.5.0, this parameter is required; the default VOD access region is cn-shanghai.
    vidAuth.setQuality("Selected definition") //"AUTO" represents adaptive bitrate.

    VidSts

    VidSts vidSts = new VidSts();
    vidSts.setVid("Vid info");// Required parameter: Video ID. vidSts.setAccessKeyId("<yourAccessKeyId>");// Required parameter: Access key ID of the STS temporary AK pair, generated by calling the AssumeRole API of STS.  vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required parameter: Access key of the STS temporary AK pair, generated by calling the AssumeRole API of STS.  vidSts.setSecurityToken("<yourSecurityToken>");// Required parameter: STS security token, generated by calling the AssumeRole API of STS.  vidSts.setRegion("Access region");// Required parameter: VOD access region; default is cn-shanghai.
    vidSts.setQuality("Selected definition") //"AUTO" represents adaptive bitrate.

    UrlSource

    UrlSource urlSource = new UrlSource();
    urlSource.setUri("Playback address");// Required parameter: Playback address, which can be a third-party VOD address or an Alibaba Cloud VOD playback address.
  3. Defina os parâmetros da tarefa.

    Nota

    Aplica-se apenas a vídeos com múltiplos bitrates. Escolha um entre setDefaultBandWidth, setDefaultResolution ou setDefaultQuality.

    PreloadConfig preloadConfig = new PreloadConfig();
    // Set preloading bitrate for multi-bitrate streams.
    preloadConfig.setDefaultBandWidth(400000);
    // Set preloading resolution for multi-bitrate streams.
    preloadConfig.setDefaultResolution(640 * 480);
    // Set preloading quality for multi-bitrate streams.
    preloadConfig.setDefaultQuality("FD");
    // Set preloading duration.
    preloadConfig.setDuration(1000);
  4. Adicione o listener da tarefa.

    Expandir para visualizar o código

    /**
     * Preloading listener implementation.
     */
    private static class PreloadListenerImpl extends OnPreloadListener {
    
        @Override
        public void onError(@NonNull String taskId, @NonNull String urlOrVid, @NonNull ErrorInfo errorInfo) {
            // Loading error.
        }
    
        @Override
        public void onCompleted(@NonNull String taskId, @NonNull String urlOrVid) {
            // Loading completed.
        }
    
        @Override
        public void onCanceled(@NonNull String taskId, @NonNull String urlOrVid) {
           // Loading canceled.
        }
    }
  5. Construa a tarefa e adicione à instância MediaLoaderV2 para iniciar o pré-carregamento.

    VidAuth (recomendado)

    // Build preloading.
    PreloadTask mPreloadTask = new PreloadTask(vidAuth, preloadConfig);
    // Get MediaLoaderV2 instance.
    MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance();
    // Add task and start preloading.
    String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl)

    VidSts

    // Build preloading.
    PreloadTask mPreloadTask = new PreloadTask(vidSts, preloadConfig);
    // Get MediaLoaderV2 instance.
    MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance();
    // Add task and start preloading.
    String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl);

    UrlSource

    // Build preloading.
    PreloadTask mPreloadTask = new PreloadTask(urlSource, preloadConfig);
    // Get MediaLoaderV2 instance.
    MediaLoaderV2 mediaLoaderV2 = MediaLoaderV2.getInstance();
    // Add task and start preloading.
    String taskId = mediaLoaderV2.addTask(mPreloadTask, PreloadListenerImpl)
  6. Opcional: Gerencie tarefas.

    mediaLoaderV2.cancelTask(taskId);// Cancel preloading task with specified task ID.
    mediaLoaderV2.pauseTask(taskId);// Pause preloading task with specified task ID.
    mediaLoaderV2.resumeTask(taskId);// Resume preloading task with specified task ID.
  7. Opcional: Exclua arquivos carregados.

    Exclua arquivos carregados conforme necessário para economizar espaço. O Android Player SDK não fornece uma interface de exclusão; exclua arquivos do diretório de carregamento em seu aplicativo.

Pré-carregamento dinâmico

A estratégia de pré-carregamento dinâmico permite que os integradores controlem tanto o cache do vídeo atualmente em reprodução quanto o número e o cache dos itens pré-carregados, equilibrando a experiência de reprodução e a sobrecarga de custos.

Expandir para visualizar o código

// Enable recommended configuration and dynamic preloading.
aliListPlayer.setPreloadScene(IListPlayer.SceneType.SCENE_SHORT);

// Configure baseline preloading duration.
// Set preloading duration to 1000ms.
PreloadConfig config = new PreloadConfig();
config.mPreloadDuration = 1000;
aliListPlayer.updatePreloadConfig(config);

// Configure number of preloads, supporting bidirectional.
// 1 for forward preloads, 3 for backward preloads.
aliListPlayer.setPreloadCount(1, 3);

// Configure dynamic preloading decrement offset.
aliListPlayer.enablePreloadStrategy(IListPlayer.StrategyType.STRATEGY_DYNAMIC_PRELOAD_DURATION, true);
aliListPlayer.setPreloadStrategy(IListPlayer.StrategyType.STRATEGY_DYNAMIC_PRELOAD_DURATION, "{\"algorithm\": \"sub\",\"offset\": \"200\"}");

Pré-carregamento de vídeo HLS com múltiplos bitrates

Em cenários de reprodução de vídeo HLS com múltiplos bitrates + listPlayer, os integradores podem pré-carregar streams correspondentes à definição de reprodução atual e escolher modos de pré-carregamento com base nas necessidades do negócio.

Expandir para visualizar os modos de pré-carregamento suportados

  /**
   * Default configuration, play and preload default bitrate.
   */
  MultiBitratesMode_Default(0),

  /**
   * First frame priority configuration, decrease first frame cost. Only play bitrate of the HLS stream which has been preloaded.
   */
  MultiBitratesMode_FCPrio(1),

  /**
   * Balance first frame and playback smoothness, play the same bitrate before and after moveToNext, and prioritize first frame performance.
   */
  MultiBitratesMode_FC_AND_SMOOTH(2),

  /**
   * Playback smoothness priority configuration, play the same bitrate before and after moveToNext.
   */
  MultiBitratesMode_SmoothPrio(3);

Expandir para visualizar o código de integração

// Select multi-bitrate loading mode.
aliListPlayer.SetMultiBitratesMode(preLoadMode);

// (Optional) Select startup bitrate.
aliListPlayer.setDefaultBandWidth(defaultBandWidth)

// (Optional) In onPrepared callback, select ABR mode.
aliListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
    @Override
    public void onPrepared() {
        // ABR only affects multi-bitrate m3u8.
        aliListPlayer.selectTrack(-1);
    }
});

Obter velocidade de download

Obtenha a velocidade atual de download de vídeo através do callback onInfo, implementado pela interface getExtraValue. Exemplo:

aliPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
    @Override
    public void onInfo(InfoBean infoBean) {
        if(infoBean.getCode() == InfoCode.CurrentDownloadSpeed){
            // Current download speed.
            long extraValue = infoBean.getExtraValue();
        }
    }
});

Recursos de rede

HTTPDNS

O HTTPDNS resolve nomes de domínio via HTTP para servidores específicos, reduzindo riscos de sequestro de DNS e fornecendo resolução mais rápida e estável.

O ApsaraVideo Player SDK fornece HTTPDNS aprimorado para domínios do Alibaba Cloud CDN, suportando agendamento preciso de CDN e resolução em tempo real.

Exemplo de uso do HTTPDNS aprimorado

O HTTPDNS aprimorado fornece serviços apenas para domínios do Alibaba Cloud CDN. Certifique-se de que seu domínio seja um domínio do Alibaba Cloud CDN e esteja configurado corretamente. Para adicionar domínios CDN no VOD, consulte Adicionar domínio acelerado. Alibaba Cloud CDN.

// Enable enhanced HTTPDNS.
AliPlayerGlobalSettings.enableEnhancedHttpDns(true);
// Optional: Add HTTPDNS pre-resolution domains.
DomainProcessor.getInstance().addPreResolveDomain("player.***alicdn.com");

HTTP/2

Nota

O Android Player SDK ativa o HTTP/2 por padrão a partir da versão 5.5.0.0.

O Android Player SDK suporta o protocolo HTTP/2, que usa multiplexação para evitar bloqueio de cabeça de linha e melhorar o desempenho de reprodução. Exemplo:

AliPlayerGlobalSettings.setUseHttp2(true);

HTTP/3

Nota
  • O IETF QUIC tornou-se um padrão oficial em 2022. O Android Player SDK suporta apenas IETF QUIC h3-v1 e não Google QUIC.

  • Se a conexão HTTP/3 expirar ou falhar, ela sofrerá degradação automática para HTTP/2.

O Android Player SDK suporta o protocolo HTTP/3. Você precisa preencher um formulário para solicitar a ativação do HTTP/3 para seu domínio, permitindo que vídeos acelerados através deste domínio no VOD suportem reprodução HTTP/3. Em seguida, configure o player para usar HTTP/3 nas solicitações para obter melhor resiliência em redes fracas. Exemplo:

// Get configuration first.
PlayerConfig config = aliPlayer.getConfig();
// Request using HTTP/3 protocol.
config.mEnableHttp3 = true;
....// Other settings.
// Set configuration for the current player instance.
aliPlayer.setConfig(config);

Pré-conexão TCP HTTP

Para solicitações de reprodução de vídeo HTTP (não HTTPS), estabelecer conexões TCP antecipadamente melhora significativamente a experiência do usuário, reduz o tempo de conexão de rede, garante reprodução imediata e contínua e otimiza o uso de recursos de rede e sistema. Uso:

// Domain format is host[:port]; port is optional. Separate multiple domains with semicolons (;).
// Global setting.
// Full interface uses the current string each time it's set (more - add, less - remove). Empty string stops pre-connection.
AliPlayerGlobalSettings.setOption(AliPlayerGlobalSettings.SET_PRE_CONNECT_DOMAIN, "domain1;domain2");

Plugins pagos

Download de vídeo

Nota

Para exemplos de código detalhados, consulte o módulo API-Example Download de vídeo e reprodução offline (Download). Este projeto de exemplo baseado em Java para o ApsaraVideo Player SDK para Android ajuda os desenvolvedores a dominar rapidamente os principais recursos de integração do SDK.

O Android Player SDK fornece um recurso de download de vídeo para serviços VOD, permitindo que os usuários armazenem vídeos em cache localmente usando o ApsaraVideo Player. Ele oferece dois métodos de download: download padrão e download seguro.

  • Download padrão

    Os dados de vídeo baixados não são criptografados pelo Alibaba Cloud e podem ser reproduzidos por players de terceiros.

  • Download seguro

    Os dados de vídeo baixados são criptografados pelo Alibaba Cloud. Players de terceiros não podem reproduzi-los. Apenas o ApsaraVideo Player pode reproduzi-los.

Instruções de uso

  • Apenas os métodos VidSts e VidAuth suportam download de vídeo.

  • Para usar o recurso de download de vídeo do player, ative e configure o modo de download no console VOD. Para etapas detalhadas, consulte Download offline.

  • O download de vídeo suporta downloads retomáveis.

Procedimento

  1. Opcional: Configure o arquivo de verificação de criptografia para download seguro. Necessário apenas para download seguro; não é necessário para download padrão.

    Nota

    Certifique-se de que o arquivo de verificação de criptografia configurado corresponda às informações do seu aplicativo; caso contrário, o download de vídeo falhará.

    Para download seguro, configure o arquivo de chave gerado no console VOD no Player SDK para verificação de descriptografia durante o download e reprodução de vídeo. Para geração de arquivo de chave, consulte Ativar download seguro.

    Recomendamos configurar isso uma vez no Application. Exemplo:

    PrivateService.initService(getApplicationContext(),  "Path to encryptedApp.dat file"); // We recommend storing the encryptedApp.dat verification file on the phone and setting its local file path here.
  2. Crie e defina o downloader.

    Crie um downloader usando AliDownloaderFactory. Exemplo:

    AliMediaDownloader mAliDownloader = null;
    ......
    // Create downloader.
    mAliDownloader = AliDownloaderFactory.create(getApplicationContext());
    // Configure download save path.
    mAliDownloader.setSaveDir("Save folder path");
  3. Defina listeners de eventos.

    O downloader fornece múltiplos listeners de eventos. Exemplo:

    Expandir para visualizar o código

    mAliDownloader.setOnPreparedListener(new AliMediaDownloader.OnPreparedListener() {
       @Override
       public void onPrepared(MediaInfo mediaInfo) {
           // Download item prepared successfully.
       }
    });
    mAliDownloader.setOnProgressListener(new AliMediaDownloader.OnProgressListener() {
       @Override
       public void onDownloadingProgress(int percent) {
           // Download progress percentage.
       }
       @Override
       public void onProcessingProgress(int percent) {
           // Processing progress percentage.
       }
    });
    mAliDownloader.setOnErrorListener(new AliMediaDownloader.OnErrorListener() {
       @Override
       public void onError(ErrorInfo errorInfo) {
           // Download error.
       }
    });
    mAliDownloader.setOnCompletionListener(new AliMediaDownloader.OnCompletionListener() {
       @Override
       public void onCompletion() {
           // Download successful.
       }
    });
  4. Prepare a fonte de download.

    Prepare a fonte de download usando o método prepare. As fontes de download suportam os métodos VidSts e VidAuth. Exemplos:

    • VidSts

      // Create VidSts
      VidSts aliyunVidSts = new VidSts();
      aliyunVidSts.setVid("Vid information"); // Video ID (VideoId).
      aliyunVidSts.setAccessKeyId("<yourAccessKeyId>"); // AccessKey ID of the temporary STS AccessKey pair, generated by calling the AssumeRole operation of the Security Token Service (STS).
      aliyunVidSts.setAccessKeySecret("<yourAccessKeySecret>"); // AccessKey secret of the temporary STS AccessKey pair, generated by calling the AssumeRole operation of the Security Token Service (STS).
      aliyunVidSts.setSecurityToken("<yourSecurityToken>"); // Security Token Service (STS) token, generated by calling the AssumeRole operation of the Security Token Service (STS).
      aliyunVidSts.setRegion("region"); // The region of the video-on-demand (VOD) service. Default value: cn-shanghai.
      // If you have enabled HLS encryption parameter pass-through in the VOD console and the default parameter name is MtsHlsUriToken,
      // you must set the config and pass it into the vid, as shown below.
      // If you have not enabled HLS encryption parameter pass-through in the VOD console, skip the following code.
      VidPlayerConfigGen vidConfig = new VidPlayerConfigGen();
      vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>");
      aliyunVidSts.setPlayerConfig(vidConfig);
              
      
      // Prepare the download source
      mAliDownloader.prepare(aliyunVidSts)
    • VidAuth

      // Create VidAuth.
      VidAuth vidAuth = new VidAuth();
      vidAuth.setVid("Vid info");// Video ID.
      vidAuth.setPlayAuth("<yourPlayAuth>");// Playback credential, generated by calling VOD GetVideoPlayAuth API.
      vidAuth.setRegion("Access region");// For player SDK version 5.5.5.0 and later, this parameter is deprecated and not required; the player automatically parses the region. For versions before 5.5.5.0, this parameter is required; VOD access region default is cn-shanghai.
      // If you enabled HLS standard encryption parameter pass-through in VOD console with default parameter name MtsHlsUriToken, set config and pass it to vid as follows.
      VidPlayerConfigGen vidConfig = new VidPlayerConfigGen();
      vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>");
      vidAuth.setPlayerConfig(config);
      // Prepare download source.
      mAliDownloader.prepare(vidAuth);
    Nota
    • O formato do arquivo de origem corresponde ao formato do arquivo baixado; alterá-lo não é suportado.

    • Se você ativou a passagem de parâmetros de criptografia padrão HLS no console VOD com o nome de parâmetro padrão MtsHlsUriToken, consulte Passagem de parâmetros de criptografia padrão HLS, então defina o valor MtsHlsUriToken na fonte VOD conforme mostrado acima.

  5. Após a preparação bem-sucedida, selecione o item de download e inicie o download.

    Após a preparação bem-sucedida, o método OnPreparedListener é chamado. O TrackInfo retornado contém informações como a definição do stream de vídeo. Selecione um Track para download. Exemplo:

    public void onPrepared(MediaInfo mediaInfo) {
        // Download item prepared successfully.
        List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
        // For example: download the first TrackInfo.
        mAliDownloader.selectItem(trackInfos.get(0).getIndex());
        // Start download.
        mAliDownloader.start();
    }
  6. (Opcional) Atualize a fonte de download.

    Para evitar a expiração de VidSts e VidAuth, você pode atualizar as informações da fonte de download e iniciar o download. Exemplo:

    // Update download source.
    mAliDownloader.updateSource(VidSts);
    // Start download.
    mAliDownloader.start();
  7. Após sucesso ou falha no download, libere o downloader.

    Após o sucesso do download, chame release no callback onCompletion ou onError para liberar o downloader. Exemplo:

    mAliDownloader.stop();
    mAliDownloader.release();
  8. Opcional: Exclua arquivos baixados.

    Você pode excluir arquivos baixados durante ou após o download. Exemplo:

    // Delete file via object.
    mAliDownloader.deleteFile();
    // Delete via static method; returns 0 if successful.
    AliDownloaderFactory.deleteFile("Path to download folder","Video ID","Video format","Downloaded video index");

Próximos passos

Vídeos baixados podem ser reproduzidos usando o ApsaraVideo Player. Etapas:

  1. Após a conclusão do download, obtenha o caminho absoluto do arquivo de vídeo.

    String path = mAliDownloader.getFilePath();
  2. Defina o caminho absoluto via VOD UrlSource para reprodução.

     UrlSource urlSource = new UrlSource();
            urlSource.setUri("Playback address");// Set absolute path of downloaded video.
            aliPlayer.setDataSource(urlSource);

Reprodução criptografada

Vídeos VOD suportam criptografia padrão HLS, criptografia proprietária do Alibaba Cloud e criptografia DRM. Vídeos ao vivo suportam apenas criptografia DRM. Para reprodução criptografada, consulte Reprodução criptografada.

Reprodução Native RTS

O Android Player SDK integra o Native RTS SDK para transmissão ao vivo com latência ultrabaixa. Implementar pull de stream RTS no Android.

Referências