Google之ExoPlayer简单使用
ExoPlayer的简单介绍
ExoPlayer是一个由Google开发的,基于Android低级媒体API构建的开源应用级媒体播放器。
可以播放DASH,SmoothStreaming和HLS自适应流(这些都是流媒体传输解决方案);支持的格式有MP4,M4A,FMP4,WebM,MKV,MP3,Ogg,WAV,MOEG-PS,FLV和ADTS等格式,大部分格式并不常见。
优点缺点(这里是和MediaPlayer对比):
优点:
- 额外支持基于HTTP的动态自适应流(DASH)和SmoothStreaming这两种流媒体的播放。
- 支持高级HLS功能,两个视屏无缝合并播放,可以连接和循环媒体。
- 支持Android4.4(API级别19)以上
- 可以更好的自定义,自定义范围包括播放功能和样式。
缺点:缺点就是比较耗电,耗电什么程度就不知道了,不影响使用。
先看效果
具体使用步骤
-
第一步:就是添加依赖,和其他第三方一样,
在工程级的built.gradle中:
repositories {
google()
jcenter()
}项目级的build.gradle中:
implementation ‘com.google.android.exoplayer:exoplayer:2.X.X’
(如果是低版本屎丢丢,没有implementation,修改为compile)要使用java8(项目级的build.gradle中android之下): compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
} -
在xml文件中添加组件
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/playerView"
android:layout_width="match_parent"
android:layout_height="100dp"
/>
- Activity中使用
//使用ButterKnife找到组件
@BindView(R.id.playerView)
PlayerView playerView;
//创建play实例
player = ExoPlayerFactory.newSimpleInstance(this);
//用工厂设置资源
Uri videoUri = Uri.parse("https://media.w3.org/2010/05/sintel/trailer.mp4");
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "applicationName"));//这里Util也是ExoPlayer自带的,应用名字随便写的
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri);
//将播放器Player和View关联起来
playerView.setPlayer(player);
//准备加载播放资源
player.prepare(concatenatingMediaSource);
//还可以设置加载好了就播放
player.setPlayWhenReady(true);
//可以添加一些监听器
player.addVideoListener(new VideoListener() {});
player.addListener(new Player.EventListener() {});
记得回收
@Override
protected void onDestroy() {
super.onDestroy();
player.release();
}
到此使用ExoPlayer播放一个简单的mp4就完成了。
如果是链接地址播放,记得加清单网络访问权限。
后续:可以设置多个视屏连在一起播放,就像一个个视屏片段。
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri);
ExtractorMediaSource mediaSource1 = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri1);
ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource(mediaSource, mediaSource1);
//加载list资源
player.prepare(concatenatingMediaSource);