Google之ExoPlayer簡單使用
- ExoPlayer的簡單介紹
- 優點缺點(這裡是和MediaPlayer對比):
- 先看效果
- 具體使用步驟
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);