寫在前面
在Android裝置中,播放視訊和音樂是非常普遍的。Android架構提供了一個對于媒體的操作的最省代碼的解決方案:
MediaPlayer。它提供了低等級的媒體API,例如:
MediaCodec,
AudioTrack MediaDrm,可以用于建立自定義媒體播放的解決方案。
但是MediaPlayer的api實在是但太難用了,擴充性也不好。是以我們可以用諸如
ijkplayer,
VLC以及
ExoPlayer。本文并不是講述ExoPlayer如何使用的,而是一款基于ExoPlayer的VideoView。ExoPlayerVideoView旨在提供一個快捷的視訊播放布局的解決方案。
概覽

亮度調節
控制器
快進快退
橫屏
豎屏
音量
開始
ExoPlayerView 是一個基于
的視訊播放器,并且做了很多封裝。
ExoPlayerView是在實際工作中的産物,可能并無法完全滿足各位的實際工作中的要求,但可以借鑒下。
特性
1.提供了4種視訊适應模式:
fit , fit_width , fit_height 和 none。
2.自動處理音頻焦點問題。
3.可以根據傳感器自動處理視訊方向問題。
4.支援簡單的手勢操作,如快進快退,調節音量。
用法
導入
在
build.gradle
中加入
compile 'com.jarvanmo:exoplayerview:1.0.0'
ExoPlayerView 可以直接播放如mp4,m3u8 等簡單視訊,可以用于直播.
在布局檔案中引入 ExoVideoView:
<com.jarvanmo.exoplayerview.ui.ExoVideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="300dp"
app:useController="true"
app:resizeMode="none"
app:orientationAuto="true"
/>
Play
播放一個視訊:
videoView.play(mediaSource);
如果你直接調用了上面的方法,ExoVideoView可以自動建立ExoPlayer.
當然了, 你也可以自己建立ExoPlayer;
videoView.setPlayer(player);
也可以從指定位置播放:
videoView.play(mediaSource,where);
注意:不要忘記釋放ExoPlayer:
videoView.releaseSelfPlayer();
可以通過如下方式為視訊設定一個顯示名稱:
mediaSource.setDisplayName("LuYu YouYue");
或者
videoView.setDisplayName("LuYu YouYue");
管理ExoVideoView方向
如果你為ExoVideoView設定了一個非空
OrientationListener
,ExoVideoView可以通過感器自動
變換方向。
videoView.setOrientationListener(new ExoVideoPlaybackControlView.OrientationListener() {
@Override
public void onOrientationChange(@ExoVideoPlaybackControlView.SensorOrientationType int orientation) {
if(orientation == SENSOR_PORTRAIT){
changeToPortrait();
}else if(orientation == SENSOR_LANDSCAPE){
changeToLandscape();
}
}
});
隻有當在controller中的context是Activity的時候,ExoVideoView才會調用:
activity.setRequestedOrientation()
全屏按鈕也是如此。
也可以通過如下方式更改ExoVideoView方向:
videoView.toggleControllerOrientation();
videoView.setPortrait(true);
處理傳回事件
在activity:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
if(videoView.isPortrait()){
finish();
return false;
}else {
videoView.toggleControllerOrientation();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
當 controller 中的傳回鍵鈕被點選了:
videoView.setBackListener(new ExoVideoPlaybackControlView.ExoClickListener() {
@Override
public boolean onClick(View view, boolean isPortrait) {
if(isPortrait){
finish();
}
return false;
}
});
如果
onClick()
傳回了true,它會攔截controller中的事件.如果傳回的是false 并且你設定了一個非空的OrientationListener,
ExoVideoView 如果處于橫屏,ExoVideoView将嘗試變回豎屏并調用
OrientationLister.onOrientationChange()
。
Others
你也可以在橫屏的時候加入一個自定義布局:
videoView.addViewToControllerWhenLandscape(view);
你添加的布局将被加入FrameLayout中.
提示
永遠不要忘記去釋放ExoPlayer.
videoView.releaseSelfPlayer();
or
player.release();
ExoVideoView 也支援手勢操作, 比如說左滑調亮度,右滑調音量,也可以快近或後退。
app目錄下是demo。
ExoPlayerVideoView傳送門,歡迎star。