Android视频播放器ExoPlayer使用入门

wshunli
2018-06-23 / 0 评论 / 1,113 阅读 / 正在检测是否收录...

EXOPlayer 是Google 官方开源的一款 Android 播放器,支持本地或者网络的音频和视频播放,支持 DASH、HLS 等流媒体协议,但是不支持 rtsp、rtmp 协议。

EXOPlayer 仓库地址:https://github.com/google/ExoPlayer

Google 的亲儿子,还是要学习下啊。

引入依赖

引入依赖可以一次性全部引入所有依赖:

dependencies {
    implementation 'com.google.android.exoplayer:exoplayer:2.X.X'
}

也可以根据需要引入不同模块。

dependencies {
    implementation 'com.google.android.exoplayer:exoplayer-core:2.X.X'
    implementation 'com.google.android.exoplayer:exoplayer-dash:2.X.X'
    implementation 'com.google.android.exoplayer:exoplayer-hls:2.X.X'
    implementation 'com.google.android.exoplayer:exoplayer-smoothstreaming:2.X.X'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.X.X'
}

入门使用

EXOPlayer 使用是非常简单的,首先添加播放器控件。

<com.google.android.exoplayer2.ui.SimpleExoPlayerView
    android:id="@+id/exoView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

然后初始化播放器。

private void initPlayer() {
    //1. 创建一个默认的 TrackSelector
    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTackSelectionFactory =
            new AdaptiveTrackSelection.Factory(bandwidthMeter);
    TrackSelector trackSelector =
            new DefaultTrackSelector(videoTackSelectionFactory);
    //2.创建ExoPlayer
    simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
    //3.创建SimpleExoPlayerView
    simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exoView);
    //4.为SimpleExoPlayer设置播放器
    simpleExoPlayerView.setPlayer(simpleExoPlayer);
    simpleExoPlayer.setPlayWhenReady(true);
}

最后添加视频资源就可以播放了。

DataSource.Factory mediaDataSourceFactory = new DefaultDataSourceFactory(this,
        Util.getUserAgent(this, "ExoPlayerDemo"));
MediaSource mediaSource = new ExtractorMediaSource.Factory(mediaDataSourceFactory).createMediaSource(Uri.parse("http://streams.wshunli.com/videos/dyys_x264.mp4"));
simpleExoPlayer.prepare(mediaSource);

注意添加网络权限,最终效果:

exoplayer-result

参考资料
1、EXOPlayer简要学习及应用 - CSDN博客
https://blog.csdn.net/s1991721/article/details/77587308
2、ExoPlayer开发指南(官方文档翻译) - CSDN博客
https://blog.csdn.net/u014606081/article/details/76181049
3、Google Exoplayer 之全面认识 - Android - 掘金
https://juejin.im/entry/5884061f128fe1006c34ea43
4、ExoPlayer2.5 的简单使用 - 简书
https://www.jianshu.com/p/c9b136fc16c7
6、ExoPlayer的使用介绍 - 简书
https://www.jianshu.com/p/628481250b59

0

评论 (0)

取消