首页 > 解决方案 > 来自 Android 资源的 Android Exo Player Play .m3u8

问题描述

我无法从像http://example.com/file.m3u8这样的网络服务器播放 .m3u8 文件

我已经在 android 资源中添加了播放列表文件,但它没有播放。

如何从本地资源播放相同的文件。

谢谢,

标签: androidexoplayerexoplayer2.x

解决方案


来自ExoPlayer 演示

  public void init(Context context, PlayerView playerView) {
    // Create a default track selector.
    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory =
        new AdaptiveTrackSelection.Factory(bandwidthMeter);
    TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

    // Create a player instance.
    player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);

    // Bind the player to the view.
    playerView.setPlayer(player);

    // This is the MediaSource representing the content media (i.e. not the ad).
    String contentUrl = context.getString(R.string.content_url);
    MediaSource contentMediaSource =
        buildMediaSource(Uri.parse(contentUrl), /* handler= */ null, /* listener= */ null);

    // Compose the content media source into a new AdsMediaSource with both ads and content.
    MediaSource mediaSourceWithAds =
        new AdsMediaSource(
            contentMediaSource,
            /* adMediaSourceFactory= */ this,
            adsLoader,
            playerView.getOverlayFrameLayout(),
            /* eventHandler= */ null,
            /* eventListener= */ null);

    // Prepare the player with the source.
    player.seekTo(contentPosition);
    player.prepare(mediaSourceWithAds);
    player.setPlayWhenReady(true);
  }

字符串.xml:

<string name="content_url"><![CDATA[https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8]]></string>

更新:我不确定使用本地存储中的 *.m3u8 文件是否是个好主意,但您可以使用 apk 中的媒体文件:

1) 生的

 MediaSource contentMediaSource = buildMediaSource(
 RawResourceDataSource.buildRawResourceUri(R.raw.sample_video), 
/* handler= */ null, /* listener= */ null);

2) 资产

MediaSource contentMediaSource = buildMediaSource(
Uri.fromFile(new File("//android_asset/sample_video.mp4")), 
/* handler= */ null, /* listener= */ null);

推荐阅读