一、緩存
1、使用ExoPlayer自帶的緩存機制(比對完整的url位址,相同則使用本地緩存檔案播放,視訊位址具有時效性參數時無法正确緩存)
建立緩存檔案夾
public class CachesUtil {
public static String VIDEO = "video";
/**
* 擷取媒體緩存檔案
*
* @param child
* @return
*/
public static File getMediaCacheFile(String child) {
String directoryPath = "";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 外部儲存可用
directoryPath = MyApplication.getContext().getExternalFilesDir(child).getAbsolutePath();
} else {
directoryPath = MyApplication.getContext().getFilesDir().getAbsolutePath() + File.separator + child;
}
File file = new File(directoryPath);
//判斷檔案目錄是否存在
if (!file.exists()) {
file.mkdirs();
}
LogUtil.d(TAG, "getMediaCacheFile ====> " + directoryPath);
return file;
}
}
建立帶緩存的資料解析工廠
// 測量播放帶寬,如果不需要可以傳null
TransferListener<? super DataSource> listener = new DefaultBandwidthMeter();
DefaultDataSourceFactory upstreamFactory = new DefaultDataSourceFactory(this, listener, new DefaultHttpDataSourceFactory("MyApplication", listener));
// 擷取緩存檔案夾
File file = CachesUtil.getMediaCacheFile(CachesUtil.VIDEO);
Cache cache = new SimpleCache(file, new NoOpCacheEvictor());
// CacheDataSinkFactory 第二個參數為單個緩存檔案大小,如果需要緩存的檔案大小超過此限制,則會分片緩存,不影響播放
DataSink.Factory cacheWriteDataSinkFactory = new CacheDataSinkFactory(cache, Long.MAX_VALUE);
CacheDataSourceFactory dataSourceFactory = new CacheDataSourceFactory(cache, upstreamFactory, new FileDataSourceFactory(), cacheWriteDataSinkFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
使用帶緩存的資料解析工廠建立資源,和入門的使用一緻
Uri uri = Uri.parse(url);
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
2、使用第三方庫AndroidVideoCache進行緩存(視訊位址具有時效性參數時使用此緩存方式)
添加AndroidVideoCache依賴
dependencies {
implementation'com.danikula:videocache:2.7.0'
}
自定義緩存檔案命名規則
public class CacheFileNameGenerator implements FileNameGenerator {
private static final String TAG = "CacheFileNameGenerator";
/**
* @param url
* @return
*/
@Override
public String generate(String url) {
Uri uri = Uri.parse(url);
List<String> pathSegList = uri.getPathSegments();
String path = null;
if (pathSegList != null && pathSegList.size() > ) {
path = pathSegList.get(pathSegList.size() - );
} else {
path = url;
}
Log.d(TAG, "generate return " + path);
return path;
}
}
建立單例的AndroidVideoCache執行個體的方法
public class HttpProxyCacheUtil {
private static HttpProxyCacheServer videoProxy;
public static HttpProxyCacheServer getVideoProxy() {
if (videoProxy == null) {
videoProxy = new HttpProxyCacheServer.Builder(MyApplication.getContext())
.cacheDirectory(CachesUtil.getMediaCacheFile(CachesUtil.VIDEO))
.maxCacheSize( * * ) // 緩存大小
.fileNameGenerator(new CacheFileNameGenerator())
.build();
}
return videoProxy;
}
}
使用AndroidVideoCache進行緩存
HttpProxyCacheServer proxy = HttpProxyCacheUtil.getVideoProxy();
// 将url傳入,AndroidVideoCache判斷是否使用緩存檔案
url = proxy.getProxyUrl(url);
// 建立資源,準備播放
Uri uri = Uri.parse(url);
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
二、自定義播放界面
1、初級自定義
-
自定義PlaybackControlView播放控制界面
建立一個XML布局檔案exo_playback_control_view,在這個布局檔案裡面設計我們想要的布局樣式,在SimpleExoPlayerView控件中添加一個:
app:controller_layout_id=”布局id”
屬性。來表明該SimpleExoPlayerView所對應的PlaybackControlView的布局。
這裡要注意幾個問題:
控件的id不能随便起,這些id都是定義好的,要與exoPlayer原來PlaybackControlView的布局控件id,名稱一緻,可通過源碼檢視具體有哪些id。現在給出部分id如下:
<item name="exo_play" type="id"/><!--播放-->
<item name="exo_pause " type="id"/><!--暫停-->
<item name="exo_rew " type="id"/><!--後退-->
<item name="exo_ffwd" type="id"/><!--前進-->
<item name="exo_prev" type="id"/><!--上一個-->
<item name="exo_next" type="id"/><!--下一個-->
<item name="exo_repeat_toggle " type="id"/><!--重複模式開關-->
<item name="exo_duration " type="id"/><!--視訊總時長-->
<item name="exo_position " type="id"/><!--目前播放位置-->
<item name="exo_progress " type="id"/><!--播放總時長-->
布局的控件數量可以少(比如上一個,下一個這個功能我不想要,就可以不寫,也就不會展示出來),但不能多,也不能出現沒有定義的id。比如說:想在控制布局上添加一個展開全屏的按鈕,那就實作不了
*DefaultTimeBar預設進度條
可以通過xml設定他的顔色,高度,大小等等
app:bar_height="2dp"
app:buffered_color="#ffffff"
app:played_color="#c15d3e"
app:scrubber_color="#ffffff"
app:scrubber_enabled_size="10dp"
app:unplayed_color="#cdcdcd"
2、進階自定義
當我們需要添加更多按鈕,比如全屏按鈕時,初級自定義就沒辦法滿足我們的需求,這是需要我們自定義重寫SimpleExoPlayerView和PlaybackControlView這兩個類。這裡以添加全屏按鈕為例。
* 自定義PlaybackControlView,添加全屏按鈕,點選切換橫屏
* 自定義SimpleExoPlayerView,使用自定義PlaybackControlView
* 切換橫屏時隐藏其他布局,隻顯示視訊控件,達到全屏效果
複制PlaybackControlView代碼,建立ExoVideoPlayBackControlView為我們自定義視訊控制類,複制SimpleExoPlayerView代碼,建立ExoVideoPlayView為我們自定義視訊播放控件,将其中使用的控制器換成ExoVideoPlayBackControlView。為ExoVideoPlayBackControlView建立XML檔案view_exo_video_play_back_control,添加全屏按鈕,再添加全屏播放時的标題欄布局和控制布局,具體界面按需求實作,并将他們隐藏,在全屏播放時在顯示。這裡全屏按鈕的id不在預設定義的id清單中,是以使用”@+id/”自己定義
<ImageButton
android:id="@+id/exo_fill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@null"
android:padding="5dp"
android:scaleType="centerInside"
android:src="@drawable/selector_video_fill" />
在構造方法中初始我們的布局和控件,給全屏按鈕設定點選事件,點選時橫屏,調整界面達成全屏的效果
public class ExoVideoPlayBackControlView extends FrameLayout {
static {
ExoPlayerLibraryInfo.registerModule("goog.exo.ui");
}
...
private final ComponentListener componentListener;// 事件監聽
private final View fillButton; //全屏按鈕
private final View exoPlayerControllerBottom; // 預設控制器
private final View exoPlayerControllerTopLandscape; // 全屏标題
private final View exoPlayerControllerBottomLandscape; // 全屏控制器
...
public ExoVideoPlayBackControlView(Context context, AttributeSet attrs, int defStyleAttr,AttributeSet playbackAttrs) {
super(context, attrs, defStyleAttr);
int controllerLayoutId = R.layout.view_exo_video_play_back_control;
componentListener = new ComponentListener();
...
fillButton = findViewById(R.id.exo_fill);
if (fillButton != null) {
fillButton.setOnClickListener(componentListener);
}
exoPlayerControllerBottom = findViewById(R.id.exoPlayerControllerBottom);
exoPlayerControllerTopLandscape = findViewById(R.id.exoPlayerControllerTopLandscape);
exoPlayerControllerBottomLandscape = findViewById(R.id.exoPlayerControllerBottomLandscape);
}
...
private final class ComponentListener extends Player.DefaultEventListener implements TimeBar.OnScrubListener, OnClickListener {
...
@Override
public void onClick(View view) {
if (player != null) {
if (fillButton == view) {
// 設定橫屏
changeOrientation(SENSOR_LANDSCAPE);
}
}
...
}
}
在ExoVideoPlayBackControlView切換橫豎屏的方法中執行橫豎屏切換回調,重新設定是否豎屏參數,修改狀态欄屬性,在顯示和隐藏控制器視圖的方法中也要修改狀态欄屬性
private synchronized void changeOrientation(@OnOrientationChangedListener.SensorOrientationType int orientation) {
if (orientationListener == null) {
return;
}
// 執行回調
orientationListener.onOrientationChanged(orientation);
switch (orientation) {
case SENSOR_PORTRAIT:
// 豎屏
setPortrait(true);
showSystemStatusUi();
break;
case SENSOR_LANDSCAPE:
// 橫屏
setPortrait(false);
showSystemStatusUi();
break;
case SENSOR_UNKNOWN:
default:
break;
}
}
/**
* Shows the playback controls. If {@link #getShowTimeoutMs()} is positive then the controls will
* be automatically hidden after this duration of time has elapsed without user input.
*/
public void show() {
if (!isVisible()) {
setVisibility(VISIBLE);
// 顯示狀态欄
showSystemStatusUi();
if (visibilityListener != null) {
visibilityListener.onVisibilityChange(getVisibility());
}
updateAll();
requestPlayPauseFocus();
}
// Call hideAfterTimeout even if already visible to reset the timeout.
hideAfterTimeout();
}
/**
* Hides the controller.
*/
public void hide() {
if (isVisible()) {
setVisibility(GONE);
if (visibilityListener != null) {
visibilityListener.onVisibilityChange(getVisibility());
}
removeCallbacks(updateProgressAction);
removeCallbacks(hideAction);
hideAtMs = C.TIME_UNSET;
// 收起狀态欄,全屏播放
hideSystemStatusUi();
}
}
public void setPortrait(boolean portrait) {
this.portrait = portrait;
// 根據橫豎屏情況顯示控制器視圖
showControllerByDisplayMode();
}
/**
* 在切換橫豎屏時和顯示控制器視圖顯示狀态欄
*/
private void showSystemStatusUi() {
if (videoViewAccessor == null) {
return;
}
int flag = View.SYSTEM_UI_FLAG_VISIBLE;
videoViewAccessor.attachVideoView().setSystemUiVisibility(flag);
}
/**
* 隐藏控制器視圖時收起狀态欄,全屏播放
*/
private void hideSystemStatusUi() {
if (portrait) {
return;
}
if (videoViewAccessor == null) {
return;
}
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
if (windowManager == null) {
return;
}
int flag = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
flag |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
videoViewAccessor.attachVideoView().setSystemUiVisibility(flag);
}
/**
* 橫屏時設定橫屏頂部标題和橫屏底部控制器可見,豎屏時設定豎屏底部控制器可見
*/
private void showControllerByDisplayMode() {
if (exoPlayerControllerTopLandscape != null) {
if (portrait) {
exoPlayerControllerTopLandscape.setVisibility(INVISIBLE);
} else {
exoPlayerControllerTopLandscape.setVisibility(VISIBLE);
}
}
if (exoPlayerControllerBottom != null) {
if (portrait) {
exoPlayerControllerBottom.setVisibility(VISIBLE);
} else {
exoPlayerControllerBottom.setVisibility(INVISIBLE);
}
}
if (exoPlayerControllerBottomLandscape != null) {
if (portrait) {
exoPlayerControllerBottomLandscape.setVisibility(INVISIBLE);
} else {
exoPlayerControllerBottomLandscape.setVisibility(VISIBLE);
}
}
}
自定義切換橫豎屏監聽,在activity中定義回調,并逐層傳遞activity -> ExoVideoPlayView -> ExoVideoPlayBackControlView,在回調中隐藏除了視訊播放空間之外的控件,設定Window的flag,在隐藏顯示狀态欄時不改變原有布局
public interface OnOrientationChangedListener {
int SENSOR_UNKNOWN = -;
int SENSOR_PORTRAIT = SENSOR_UNKNOWN + ;
int SENSOR_LANDSCAPE = SENSOR_PORTRAIT + ;
@IntDef({SENSOR_UNKNOWN, SENSOR_PORTRAIT, SENSOR_LANDSCAPE})
@Retention(RetentionPolicy.SOURCE)
@interface SensorOrientationType {
}
void onChanged(@SensorOrientationType int orientation);
}
evpvAlbumPlay.setOrientationListener(new ExoVideoPlayBackControlView.OrientationListener() {
@Override
public void onOrientationChanged(int orientation) {
if (orientation == SENSOR_PORTRAIT) {
changeToPortrait();
} else if (orientation == SENSOR_LANDSCAPE) {
changeToLandscape();
}
}
});
private void changeToPortrait() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
WindowManager.LayoutParams attr = getWindow().getAttributes();
Window window = getWindow();
window.setAttributes(attr);
window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
rlTitle.setVisibility(View.VISIBLE);
llOthersAlbumPlay.setVisibility(View.VISIBLE);
}
private void changeToLandscape() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
WindowManager.LayoutParams lp = getWindow().getAttributes();
Window window = getWindow();
window.setAttributes(lp);
// 隐藏顯示狀态欄時不改變原有布局
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
rlTitle.setVisibility(View.GONE);
llOthersAlbumPlay.setVisibility(View.GONE);
}
重寫ExoVideoPlayBackControlView的onKeyDown方法,在全屏模式下點選回退按鈕,應切換回豎屏,豎屏時執行回退的回調
public class ExoVideoPlayBackControlView extends FrameLayout {
public interface ExoClickListener {
boolean onBackClick(@Nullable View view, boolean isPortrait);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (portrait) {
if (exoClickListener != null) {
exoClickListener.onBackClick(null, portrait);
}
} else {
changeOrientation(SENSOR_PORTRAIT);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
evpvAlbumPlay.setBackListener(new ExoVideoPlayBackControlView.ExoClickListener() {
@Override
public boolean onBackClick(@Nullable View view, boolean isPortrait) {
if (isPortrait) {
finish();
}
return false;
}
至此,自定義ExoPlayer,點選全屏播放的功能基本完成,不過還有一些需要完善的地方,比如在全屏播放時顯示控制器視圖,上邊的部分視圖會被狀态欄擋住,如果手機有虛拟導航欄,導航欄會遮住右邊部分視圖,是以還需要擷取狀态高度和虛拟導航欄高度,設定間距
int navigationHeight = ScreenUtil.getNavigationHeight(context);
exoPlayerControllerBottom = findViewById(R.id.exoPlayerControllerBottom);
exoPlayerControllerTopLandscape = findViewById(R.id.exoPlayerControllerTopLandscape);
exoPlayerControllerTopLandscape.setPadding(, ScreenUtil.getStatusHeight(context), navigationHeight, );
exoPlayerControllerBottomLandscape = findViewById(R.id.exoPlayerControllerBottomLandscape);
View llControllerBottomLandscape = findViewById(R.id.llControllerBottomLandscape);
llControllerBottomLandscape.setPadding(, , navigationHeight, );
timeBarLandscape.setPadding(, , navigationHeight, );
public class ScreenUtil {
private ScreenUtil() {
private ScreenUtil() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 獲得狀态欄的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 獲得NavigationHeight
*
* @param context
* @return
*/
public static int getNavigationHeight(Context context) {
int navigationHeight = ;
// 螢幕原始尺寸高度,包括虛拟功能鍵高度
int screenHeight = ;
// 擷取螢幕尺寸,不包括虛拟功能高度
int defaultDisplayHeight = ;
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
screenHeight = dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
Point outSize = new Point();
windowManager.getDefaultDisplay().getSize(outSize);
defaultDisplayHeight = outSize.y;
navigationHeight = screenHeight - defaultDisplayHeight;
return navigationHeight;
}
}
三、事件監聽
ExoPlayer的事件監聽EventListener,通過Player的addListener方法和removeListener方法添加和删除。
public interface Player {
/**
* Listener of changes in player state.
*/
interface EventListener {
/**
* Called when the timeline and/or manifest has been refreshed.
* <p>
* Note that if the timeline has changed then a position discontinuity may also have occurred.
* For example, the current period index may have changed as a result of periods being added or
* removed from the timeline. This will <em>not</em> be reported via a separate call to
* {@link #onPositionDiscontinuity(int)}.
*
* @param timeline The latest timeline. Never null, but may be empty.
* @param manifest The latest manifest. May be null.
*/
void onTimelineChanged(Timeline timeline, Object manifest);
/**
* Called when the available or selected tracks change.
*
* @param trackGroups The available tracks. Never null, but may be of length zero.
* @param trackSelections The track selections for each renderer. Never null and always of
* length {@link #getRendererCount()}, but may contain null elements.
*/
void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections);
/**
* Called when the player starts or stops loading the source.
*
* @param isLoading Whether the source is currently being loaded.
*/
void onLoadingChanged(boolean isLoading);
/**
* Called when the value returned from either {@link #getPlayWhenReady()} or
* {@link #getPlaybackState()} changes.
*
* @param playWhenReady Whether playback will proceed when ready.
* @param playbackState One of the {@code STATE} constants.
*/
void onPlayerStateChanged(boolean playWhenReady, int playbackState);
/**
* Called when the value of {@link #getRepeatMode()} changes.
*
* @param repeatMode The {@link RepeatMode} used for playback.
*/
void onRepeatModeChanged(@RepeatMode int repeatMode);
/**
* Called when the value of {@link #getShuffleModeEnabled()} changes.
*
* @param shuffleModeEnabled Whether shuffling of windows is enabled.
*/
void onShuffleModeEnabledChanged(boolean shuffleModeEnabled);
/**
* Called when an error occurs. The playback state will transition to {@link #STATE_IDLE}
* immediately after this method is called. The player instance can still be used, and
* {@link #release()} must still be called on the player should it no longer be required.
*
* @param error The error.
*/
void onPlayerError(ExoPlaybackException error);
/**
* Called when a position discontinuity occurs without a change to the timeline. A position
* discontinuity occurs when the current window or period index changes (as a result of playback
* transitioning from one period in the timeline to the next), or when the playback position
* jumps within the period currently being played (as a result of a seek being performed, or
* when the source introduces a discontinuity internally).
* <p>
* When a position discontinuity occurs as a result of a change to the timeline this method is
* <em>not</em> called. {@link #onTimelineChanged(Timeline, Object)} is called in this case.
*
* @param reason The {@link DiscontinuityReason} responsible for the discontinuity.
*/
void onPositionDiscontinuity(@DiscontinuityReason int reason);
/**
* Called when the current playback parameters change. The playback parameters may change due to
* a call to {@link #setPlaybackParameters(PlaybackParameters)}, or the player itself may change
* them (for example, if audio playback switches to passthrough mode, where speed adjustment is
* no longer possible).
*
* @param playbackParameters The playback parameters.
*/
void onPlaybackParametersChanged(PlaybackParameters playbackParameters);
/**
* Called when all pending seek requests have been processed by the player. This is guaranteed
* to happen after any necessary changes to the player state were reported to
* {@link #onPlayerStateChanged(boolean, int)}.
*/
void onSeekProcessed();
}
}
其中onPlayerStateChanged方法傳回了是否正在播放和播放狀态,播放狀态一共以下幾種:
public interface Player {
/**
* The player does not have any media to play.
*/
int STATE_IDLE = ;
/**
* The player is not able to immediately play from its current position. This state typically
* occurs when more data needs to be loaded.
*/
int STATE_BUFFERING = ;
/**
* The player is able to immediately play from its current position. The player will be playing if
* {@link #getPlayWhenReady()} is true, and paused otherwise.
*/
int STATE_READY = ;
/**
* The player has finished playing the media.
*/
int STATE_ENDED = ;
}
具體使用可參考SimpleExoPlayerView和PlaybackControlView,這兩個類中的ComponentListener類實作了這個事件監聽。