HLS

ExoPlayer 支持多种容器格式的 HLS。其中包含的音频和视频采样格式也必须受支持(有关详细信息,请参阅采样格式部分)。我们强烈建议 HLS 内容生产者生成高质量的 HLS 流,如这篇博文中所述。

功能 支持 备注
容器
MPEG-TS
FMP4/CMAF
ADTS (AAC)
MP3
隐藏式字幕 / 字幕
CEA-608
CEA-708
WebVTT
元数据
ID3
SCTE-35
内容保护
AES-128
Sample AES-128
Widevine API 19+(“cenc”方案)和 25+(“cbcs”方案)
PlayReady SL2000 仅限 Android TV
服务器控制
增量更新
阻止播放列表重新加载
阻止预加载提示加载 不包括长度未定义的字节范围
广告插入
服务器引导式广告插入(插播广告) 部分支持 仅支持带 X-ASSET-URI 的 VOD。直播流和带 X-ASSET-LIST 属性的流将在以后添加。
IMA 服务器端和客户端广告 广告插入指南
直播播放
常规直播播放
低延迟 HLS (Apple)
低延迟 HLS (Community)
通用媒体客户端数据 CMCD CMCD 集成指南

使用 MediaItem

要播放 HLS 流,您需要依赖 HLS 模块。

Kotlin

implementation("androidx.media3:media3-exoplayer-hls:1.7.1")

Groovy

implementation "androidx.media3:media3-exoplayer-hls:1.7.1"

然后,您可以为 HLS 播放列表 URI 创建一个 MediaItem 并将其传递给播放器。

Kotlin

// Create a player instance.
val player = ExoPlayer.Builder(context).build()
// Set the media item to be played.
player.setMediaItem(MediaItem.fromUri(hlsUri))
// Prepare the player.
player.prepare()

Java

// Create a player instance.
ExoPlayer player = new ExoPlayer.Builder(context).build();
// Set the media item to be played.
player.setMediaItem(MediaItem.fromUri(hlsUri));
// Prepare the player.
player.prepare();

如果您的 URI 不是以 .m3u8 结尾,您可以将 MimeTypes.APPLICATION_M3U8 传递给 MediaItem.BuildersetMimeType,以明确指示内容的类型。

媒体项的 URI 可以指向媒体播放列表或多变体播放列表。如果 URI 指向声明多个 #EXT-X-STREAM-INF 标签的多变体播放列表,则 ExoPlayer 将自动根据可用带宽和设备功能在变体之间进行适应。

使用 HlsMediaSource

对于更多自定义选项,您可以创建一个 HlsMediaSource 并直接将其传递给播放器,而不是传递 MediaItem

Kotlin

// Create a data source factory.
val dataSourceFactory: DataSource.Factory = DefaultHttpDataSource.Factory()
// Create a HLS media source pointing to a playlist uri.
val hlsMediaSource =
  HlsMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(hlsUri))
// Create a player instance.
val player = ExoPlayer.Builder(context).build()
// Set the HLS media source as the playlist with a single media item.
player.setMediaSource(hlsMediaSource)
// Prepare the player.
player.prepare()

Java

// Create a data source factory.
DataSource.Factory dataSourceFactory = new DefaultHttpDataSource.Factory();
// Create a HLS media source pointing to a playlist uri.
HlsMediaSource hlsMediaSource =
    new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(hlsUri));
// Create a player instance.
ExoPlayer player = new ExoPlayer.Builder(context).build();
// Set the HLS media source as the playlist with a single media item.
player.setMediaSource(hlsMediaSource);
// Prepare the player.
player.prepare();

访问清单

您可以通过调用 Player.getCurrentManifest 检索当前清单。对于 HLS,您应将返回的对象转换为 HlsManifestPlayer.ListeneronTimelineChanged 回调也会在清单加载时调用。对于点播内容,这将发生一次;对于直播内容,可能会发生多次。以下代码片段展示了应用如何在清单加载时执行操作。

Kotlin

player.addListener(
  object : Player.Listener {
    override fun onTimelineChanged(timeline: Timeline, @TimelineChangeReason reason: Int) {
      val manifest = player.currentManifest
      if (manifest is HlsManifest) {
        // Do something with the manifest.
      }
    }
  }
)

Java

player.addListener(
    new Player.Listener() {
      @Override
      public void onTimelineChanged(
          Timeline timeline, @Player.TimelineChangeReason int reason) {
        Object manifest = player.getCurrentManifest();
        if (manifest != null) {
          HlsManifest hlsManifest = (HlsManifest) manifest;
          // Do something with the manifest.
        }
      }
    });

播放带插播广告的 HLS 流

HLS 规范定义了 HLS 插播广告,可用于在媒体播放列表中包含插播广告信息。ExoPlayer 默认会忽略这些插播广告。可以使用 HlsInterstitialsAdsLoader 添加支持。我们并未从一开始就支持该规范的所有功能。如果您发现缺少对您的流的支持,请通过在 GitHub 上提交问题告知我们,并发送您的流 URI,以便我们添加对您的流的支持。

使用播放列表 API 与 MediaItem

播放带插播广告的 HLS 流最方便的方法是使用 HlsInterstitialsAdsLoader.AdsMediaSourceFactory 构建 ExoPlayer 实例。这允许使用基于 MediaItemPlayer 接口的播放列表 API 来播放 HLS 插播广告。

ExoPlayerMediaSource.Factory 可以在构建播放器实例时注入到构建器中

Kotlin

hlsInterstitialsAdsLoader = HlsInterstitialsAdsLoader(context)
// Create a MediaSource.Factory for HLS streams with interstitials.
var hlsMediaSourceFactory =
  HlsInterstitialsAdsLoader.AdsMediaSourceFactory(
    hlsInterstitialsAdsLoader,
    playerView,
    DefaultMediaSourceFactory(context),
  )

// Build player with interstitials media source factory
player =
  ExoPlayer.Builder(context)
    .setMediaSourceFactory(hlsMediaSourceFactory)
    .build()

// Set the player on the ads loader.
hlsInterstitialsAdsLoader.setPlayer(player)
playerView.setPlayer(player)

Java

hlsInterstitialsAdsLoader = new HlsInterstitialsAdsLoader(context);
// Create a MediaSource.Factory for HLS streams with interstitials.
MediaSource.Factory hlsMediaSourceFactory =
      new HlsInterstitialsAdsLoader.AdsMediaSourceFactory(
          hlsInterstitialsAdsLoader, playerView, new DefaultMediaSourceFactory(context));

// Build player with interstitials media source factory
player =
    new ExoPlayer.Builder(context)
        .setMediaSourceFactory(hlsMediaSourceFactory)
        .build();

// Set the player on the ads loader.
hlsInterstitialsAdsLoader.setPlayer(player);
playerView.setPlayer(player);

通过这种播放器设置,播放 HLS 插播广告只需在播放器上设置一个带有 AdsConfiguration 的媒体项即可

Kotlin

player.setMediaItem(
  MediaItem.Builder()
    .setUri("https://www.example.com/media.m3u8")
    .setAdsConfiguration(
      AdsConfiguration.Builder(Uri.parse("hls://interstitials"))
        .setAdsId("ad-tag-0") // must be unique within playlist
        .build())
    .build())

player.prepare();
player.play();

Java

player.setMediaItem(
    new MediaItem.Builder()
        .setUri("https://www.example.com/media.m3u8")
        .setAdsConfiguration(
            new AdsConfiguration.Builder(Uri.parse("hls://interstitials"))
                .setAdsId("ad-tag-0") // must be unique within playlist
                .build())
        .build());
player.prepare();
player.play();

使用基于媒体源的 API

或者,可以在不覆盖默认媒体源工厂的情况下构建 ExoPlayer 实例。为了支持插播广告,应用可以直接使用 HlsInterstitialsAdsLoader.AdsMediaSourceFactory 创建 MediaSource,并使用基于媒体源的播放列表 API 将其提供给 ExoPlayer

Kotlin

hlsInterstitialsAdsLoader = HlsInterstitialsAdsLoader(context)
// Create a MediaSource.Factory for HLS streams with interstitials.
var hlsMediaSourceFactory =
  HlsInterstitialsAdsLoader.AdsMediaSourceFactory(hlsInterstitialsAdsLoader, playerView, context)

// Build player with default media source factory.
player = new ExoPlayer.Builder(context).build();

// Create an media source from an HLS media item with ads configuration.
val mediaSource =
  hlsMediaSourceFactory.createMediaSource(
    MediaItem.Builder()
      .setUri("https://www.example.com/media.m3u8")
      .setAdsConfiguration(
        MediaItem.AdsConfiguration.Builder(Uri.parse("hls://interstitials"))
          .setAdsId("ad-tag-0")
          .build()
      )
      .build()
  )

// Set the media source on the player.
player.setMediaSource(mediaSource)
player.prepare()
player.play()

Java

HlsInterstitialsAdsLoader hlsInterstitialsAdsLoader = new HlsInterstitialsAdsLoader(context);
// Create a MediaSource.Factory for HLS streams with interstitials.
MediaSource.Factory hlsMediaSourceFactory =
    new HlsInterstitialsAdsLoader.AdsMediaSourceFactory(
      hlsInterstitialsAdsLoader, playerView, context);

// Build player with default media source factory.
player = new ExoPlayer.Builder(context).build();

// Create an media source from an HLS media item with ads configuration.
MediaSource mediaSource =
    hlsMediaSourceFactory.createMediaSource(
      new MediaItem.Builder()
        .setUri("https://www.example.com/media.m3u8")
        .setAdsConfiguration(
            new MediaItem.AdsConfiguration.Builder(Uri.parse("hls://interstitials"))
                .setAdsId("ad-tag-0")
                .build())
        .build());

// Set the media source on the player.
exoPlayer.setMediaSource(mediaSource);
exoPlayer.prepare();
exoPlayer.play();

监听广告事件

可以将 Listener 添加到 HlsInterstitialsAdsLoader,以监控有关 HLS 插播广告播放状态变化的事件。这允许应用或 SDK 跟踪已播放的广告、正在加载的资产列表、正在准备的广告媒体源,或检测资产列表加载和广告准备错误。此外,可以接收广告媒体源发出的元数据,用于精细的广告播放验证或跟踪广告播放进度。

Kotlin

class AdsLoaderListener : HlsInterstitialsAdsLoader.Listener {

  override fun onStart(mediaItem: MediaItem, adsId: Any, adViewProvider: AdViewProvider) {
    // Do something when HLS media item with interstitials is started.
  }

  override fun onMetadata(
    mediaItem: MediaItem,
    adsId: Any,
    adGroupIndex: Int,
    adIndexInAdGroup: Int,
    metadata: Metadata,
  ) {
    // Do something with metadata that is emitted by the ad media source of the given ad.
  }

  override fun onAdCompleted(
    mediaItem: MediaItem,
    adsId: Any,
    adGroupIndex: Int,
    adIndexInAdGroup: Int,
  ) {
    // Do something when ad completed playback.
  }

  // ... See JavaDoc for further callbacks of HlsInterstitialsAdsLoader.Listener.

  override fun onStop(mediaItem: MediaItem, adsId: Any, adPlaybackState: AdPlaybackState) {
    // Do something with the resulting ad playback state when stopped.
  }
}

Java

private class AdsLoaderListener
    implements HlsInterstitialsAdsLoader.Listener {

  // implement HlsInterstitialsAdsLoader.Listener

  @Override
  public void onStart(MediaItem mediaItem, Object adsId, AdViewProvider adViewProvider) {
    // Do something when HLS media item with interstitials is started.
  }

  @Override
  public void onMetadata(
      MediaItem mediaItem,
      Object adsId,
      int adGroupIndex,
      int adIndexInAdGroup,
      Metadata metadata) {
    // Do something with metadata that is emitted by the ad media source of the given ad.
  }

  @Override
  public void onAdCompleted(
      MediaItem mediaItem, Object adsId, int adGroupIndex, int adIndexInAdGroup) {
    // Do something when ad completed playback.
  }

  // ... See JavaDoc for further callbacks

  @Override
  public void onStop(MediaItem mediaItem, Object adsId, AdPlaybackState adPlaybackState) {
    // Do something with the resulting ad playback state when stopped.
  }
}

有关所有可用回调的详细文档,请参阅 HlsInterstitialsAdsLoader.Listener 的 Javadoc

然后可以将监听器添加到广告加载器

Kotlin

var listener  = AdsLoaderListener();
// Add the listener to the ads loader to receive ad loader events.
hlsInterstitialsAdsLoader.addListener(listener);

Java

AdsLoaderListener listener = new AdsLoaderListener();
// Add the listener to the ads loader to receive ad loader events.
hlsInterstitialsAdsLoader.addListener(listener);

HlsInterstitialsAdsLoader 生命周期

HlsInterstitialsAdsLoaderHlsInterstitialsAdsLoader.AdsMediaSourceFactory 的实例可以重复用于多个播放器实例,这些实例创建多个需要加载广告的媒体源。

例如,可以在 ActivityonCreate 方法中创建一个实例,然后将其重复用于多个播放器实例。只要它同时被一个播放器实例使用,这种方式就有效。这对于常见用例非常有用,即当应用进入后台时,播放器实例被销毁,然后当应用再次回到前台时,会创建一个新实例。

Kotlin

// Create the ads loader instance (for example onCreate).
hlsInterstitialsAdsLoader = HlsInterstitialsAdsLoader(context);

// Build a player and set it on the ads loader (for example onStart).
player = ExoPlayer.Builder(context).build();
hlsInterstitialsAdsLoader.setPlayer(player);

// Release the player and unset it on the ads loader (for example onStop).
player.release();
hlsInterstitialsAdsLoader.setPlayer(null);

// Build another player and set it on the ads loader (for example onStart).
player = ExoPlayer.Builder(context).build();
hlsInterstitialsAdsLoader.setPlayer(player);

// Release the player and unset it on the ads loader (for example onStop).
player.release();
hlsInterstitialsAdsLoader.setPlayer(null);

// Release the ads loader when not used anymore  (for example onDestroy).
hlsInterstitialsAdsLoader.release();

Java

// Create the ads loader instance (for example onCreate).
hlsInterstitialsAdsLoader = new HlsInterstitialsAdsLoader(context);

// Build a player and set it on the ads loader (for example onStart).
player = new ExoPlayer.Builder(context).build();
hlsInterstitialsAdsLoader.setPlayer(player);

// Release the player and unset it on the ads loader (for example onStop).
player.release();
hlsInterstitialsAdsLoader.setPlayer(null);

// Build another player and set it on the ads loader (for example onStart).
player = new ExoPlayer.Builder(context).build();
hlsInterstitialsAdsLoader.setPlayer(player);

// Release the player and unset it on the ads loader (for example onStop).
player.release();
hlsInterstitialsAdsLoader.setPlayer(null);

// Release the ads loader when not used anymore  (for example onDestroy).
hlsInterstitialsAdsLoader.release();

通常,在广告加载器上设置下一个播放器实例之前,请务必释放旧的播放器实例。一旦广告加载器本身被释放,它就不能再使用了。

自定义播放

ExoPlayer 提供了多种方式,让您可以根据应用的需求自定义播放体验。有关示例,请参阅自定义页面

禁用无分块准备

默认情况下,ExoPlayer 将使用无分块准备。这意味着 ExoPlayer 将仅使用多变体播放列表中的信息来准备流,如果 #EXT-X-STREAM-INF 标签包含 CODECS 属性,则此方法有效。

如果您的媒体分段包含未在多变体播放列表中使用 #EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS 标签声明的复用隐藏式字幕轨道,您可能需要禁用此功能。否则,这些隐藏式字幕轨道将无法被检测和播放。您可以在 HlsMediaSource.Factory 中禁用无分块准备,如以下代码片段所示。请注意,这会增加启动时间,因为 ExoPlayer 需要下载媒体分段才能发现这些额外的轨道,因此最好在多变体播放列表中声明隐藏式字幕轨道。

Kotlin

val hlsMediaSource =
  HlsMediaSource.Factory(dataSourceFactory)
    .setAllowChunklessPreparation(false)
    .createMediaSource(MediaItem.fromUri(hlsUri))

Java

HlsMediaSource hlsMediaSource =
    new HlsMediaSource.Factory(dataSourceFactory)
        .setAllowChunklessPreparation(false)
        .createMediaSource(MediaItem.fromUri(hlsUri));

创建高质量 HLS 内容

为了充分利用 ExoPlayer,您可以遵循某些准则来改进您的 HLS 内容。有关完整说明,请阅读我们关于ExoPlayer 中 HLS 播放的 Medium 博文。主要内容包括:

  • 使用精确的分段时长。
  • 使用连续媒体流;避免跨分段的媒体结构更改。
  • 使用 #EXT-X-INDEPENDENT-SEGMENTS 标签。
  • 优先使用解复用流,而不是包含视频和音频的文件。
  • 在多变体播放列表中包含所有可能的信息。

以下准则专门适用于直播流:

  • 使用 #EXT-X-PROGRAM-DATE-TIME 标签。
  • 使用 #EXT-X-DISCONTINUITY-SEQUENCE 标签。
  • 提供较长的直播窗口。一分钟或更长时间为佳。