将Vitamio的视频控制器界面进行自定义,支持视频亮度、音量的调节、全屏显示。
注意:sdk版本必须21以上(不包括21)
效果图:
在做的这个demo中主要功能:
1.改变屏幕亮度
2.改变音量大小
3.改变视频尺寸
4.改变进度
使用步骤:
1.添加库文件
vitamio官网:https://www.vitamio.org
vitamio SDK地址:https://github.com/yixia/VitamioBundle
2.引入权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3.添加库文件的活动:
<activity
android:name="io.vov.vitamio.activity.InitActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation"
android:launchMode="singleTop"
android:theme="@android:style/Theme.NoTitleBar"
android:windowSoftInputMode="stateAlwaysHidden" />
写进清单中,application里面。
MainActivity代码:
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
public class MainActivity extends AppCompatActivity {
private VideoView vv;
private CustomMediaController mCustomMediaController;
private SPUtils spUtils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置全屏显示
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//调用Vitamio.initialize(this)方法可对其进行初始化操作,该方法有一个返回值表示初始化是否成功,当初始化成功后我们再来进行进一步的操作。
if (Vitamio.initialize(this)){
vv = (VideoView) findViewById(R.id.vv);
//setVideoURI方法给VideoView设置一个网络播放地址
vv.setVideoURI(Uri.parse("http://baobab.wdjcdn.com/145076769089714.mp4"));
//MediaController是一个播放控制器(这个东西不是必须设置的,看需求)
MediaController mediaController = new MediaController(this);
vv.setMediaController(mediaController);
//自定义视频控制器
mCustomMediaController = new CustomMediaController(this, vv, this);
mCustomMediaController.setVideoName("白火锅 x 红火锅");//视频标题
mCustomMediaController.show(5000);
vv.setMediaController(mCustomMediaController);
spUtils = new SPUtils();//SharedPreferences工具类
//获取上一次保存的进度
long progress = spUtils.getShared(this, "progress");//此处使用SharedPreferences保存当前播放进度,SPUtils是我自己封装的工具类
vv.seekTo(progress);//设置视频的进度
//调用videoView的start方法就可以播放视频了(注意添加网络访问权限)
vv.start();
//显示缓冲百分比的TextView
final TextView buffer = (TextView) findViewById(R.id.buffer_percent);
//显示下载网速的TextView
final TextView net_speed = (TextView) findViewById(R.id.net_speed);
//这个方法表示监听缓冲百分比,里边的percent参数就表示当前缓冲百分比。
vv.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
buffer.setText("已缓冲:" + percent + "%");
}
});
//这个监听器我们可以用来监听缓冲的整个过程,what参数表示缓冲的时机,
// extra参数表示当前的下载网速,根据what参数我们可以判断出当前是开始缓冲还是缓冲结束还是正在缓冲,
// 开始缓冲的时候,我们将左上角的两个控件显示出来,同时让播放器暂停播放,
// 缓冲结束时将左上角两个控件隐藏起来,同时播放器开始播放,正在缓冲的时候我们就来显示当前的下载网速。
vv.setOnInfoListener(new MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
switch (what) {
//开始缓冲
case MediaPlayer.MEDIA_INFO_BUFFERING_START:
buffer.setVisibility(View.VISIBLE);
net_speed.setVisibility(View.VISIBLE);
mp.pause();
break;
//缓冲结束
case MediaPlayer.MEDIA_INFO_BUFFERING_END:
buffer.setVisibility(View.GONE);
net_speed.setVisibility(View.GONE);
mp.start();
break;
//正在缓冲
case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
net_speed.setText("当前网速:" + extra + "kb/s");
break;
}
return true;
}
});
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
//屏幕切换时,设置全屏
if (vv != null){
vv.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
}
super.onConfigurationChanged(newConfig);
}
@Override
protected void onPause() {
super.onPause();
//保存进度
spUtils.saveShared("progress",vv.getCurrentPosition(),this);
}
}
自定义视频控制器:CustomMediaController
主要实现了手势调节视频亮度、音量的加减控制。
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
/**
* Created by xhb on 2016/3/1.
* 自定义视频控制器
*/
public class CustomMediaController extends MediaController {
private static final int HIDEFRAM = 0;//控制提示窗口的显示
private GestureDetector mGestureDetector;
private ImageButton img_back;//返回按钮
private TextView mFileName;//文件名
private VideoView videoView;
private Activity activity;
private Context context;
private String videoname;//视频名称
private int controllerWidth = 0;//设置mediaController高度为了使横屏时top显示在屏幕顶端
private View mVolumeBrightnessLayout;//提示窗口
private ImageView mOperationBg;//提示图片
private TextView mOperationTv;//提示文字
private AudioManager mAudioManager;
private SeekBar progress;
private boolean mDragging;
private MediaPlayerControl player;
//最大声音
private int mMaxVolume;
// 当前声音
private int mVolume = -1;
//当前亮度
private float mBrightness = -1f;
//返回监听
private OnClickListener backListener = new OnClickListener() {
public void onClick(View v) {
if (activity != null) {
activity.finish();
}
}
};
private OnClickListener scaleListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (activity != null) {
switch (activity.getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE://横屏
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Configuration.ORIENTATION_PORTRAIT://竖屏
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
}
}
};
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
long pos;
switch (msg.what) {
case HIDEFRAM://隐藏提示窗口
mVolumeBrightnessLayout.setVisibility(View.GONE);
mOperationTv.setVisibility(View.GONE);
break;
}
}
};
private ImageView mIvScale;
//videoview 用于对视频进行控制的等,activity为了退出
public CustomMediaController(Context context, VideoView videoView, Activity activity) {
super(context);
this.context = context;
this.videoView = videoView;
this.activity = activity;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
controllerWidth = wm.getDefaultDisplay().getWidth();
mGestureDetector = new GestureDetector(context, new MyGestureListener());
}
@Override
protected View makeControllerView() {
//此处的 mymediacontroller 为我们自定义控制器的布局文件名称
View v = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(getResources().getIdentifier("mymediacontroller", "layout", getContext().getPackageName()), this);
v.setMinimumHeight(controllerWidth);
//获取控件
img_back = (ImageButton) v.findViewById(getResources().getIdentifier("mediacontroller_top_back", "id", context.getPackageName()));
mFileName = (TextView) v.findViewById(getResources().getIdentifier("mediacontroller_filename", "id", context.getPackageName()));
//缩放控件
mIvScale = (ImageView) v.findViewById(getResources().getIdentifier("mediacontroller_scale", "id", context.getPackageName()));
if (mFileName != null) {
mFileName.setText(videoname);
}
//声音控制
mVolumeBrightnessLayout = (RelativeLayout) v.findViewById(R.id.operation_volume_brightness);
mOperationBg = (ImageView) v.findViewById(R.id.operation_bg);
mOperationTv = (TextView) v.findViewById(R.id.operation_tv);
mOperationTv.setVisibility(View.GONE);
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mMaxVolume = mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//注册事件监听
img_back.setOnClickListener(backListener);
mIvScale.setOnClickListener(scaleListener);
return v;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
System.out.println("MYApp-MyMediaController-dispatchKeyEvent");
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector.onTouchEvent(event)) return true;
// 处理手势结束
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
endGesture();
break;
}
return super.onTouchEvent(event);
}
/**
* 手势结束
*/
private void endGesture() {
mVolume = -1;
mBrightness = -1f;
// 隐藏
myHandler.removeMessages(HIDEFRAM);
myHandler.sendEmptyMessageDelayed(HIDEFRAM, 1);
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
/**
* 因为使用的是自定义的mediaController 当显示后,mediaController会铺满屏幕,
* 所以VideoView的点击事件会被拦截,所以重写控制器的手势事件,
* 将全部的操作全部写在控制器中,
* 因为点击事件被控制器拦截,无法传递到下层的VideoView,
* 所以 原来的单机隐藏会失效,作为代替,
* 在手势监听中onSingleTapConfirmed()添加自定义的隐藏/显示,
*
* @param e
* @return
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
//当手势结束,并且是单击结束时,控制器隐藏/显示
toggleMediaControlsVisiblity();
return super.onSingleTapConfirmed(e);
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
//滑动事件监听
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float mOldX = e1.getX(), mOldY = e1.getY();
int y = (int) e2.getRawY();
int x = (int) e2.getRawX();
Display disp = activity.getWindowManager().getDefaultDisplay();
int windowWidth = disp.getWidth();
int windowHeight = disp.getHeight();
if (mOldX > windowWidth * 3.0 / 4.0) {// 右边滑动 屏幕 3/4
onVolumeSlide((mOldY - y) / windowHeight);
} else if (mOldX < windowWidth * 1.0 / 4.0) {// 左边滑动 屏幕 1/4
onBrightnessSlide((mOldY - y) / windowHeight);
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onDoubleTap(MotionEvent e) {
playOrPause();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return super.onFling(e1, e2, velocityX, velocityY);
}
}
/**
* 滑动改变声音大小
*
* @param percent
*/
private void onVolumeSlide(float percent) {
if (mVolume == -1) {
mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (mVolume < 0)
mVolume = 0;
// 显示
mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
mOperationTv.setVisibility(VISIBLE);
}
int index = (int) (percent * mMaxVolume) + mVolume;
if (index > mMaxVolume)
index = mMaxVolume;
else if (index < 0)
index = 0;
if (index >= 10) {
mOperationBg.setImageResource(R.drawable.volmn_100);
} else if (index >= 5 && index < 10) {
mOperationBg.setImageResource(R.drawable.volmn_60);
} else if (index > 0 && index < 5) {
mOperationBg.setImageResource(R.drawable.volmn_30);
} else {
mOperationBg.setImageResource(R.drawable.volmn_no);
}
//DecimalFormat df = new DecimalFormat("######0.00");
mOperationTv.setText((int) (((double) index / mMaxVolume) * 100) + "%");
// 变更声音
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
}
/**
* 滑动改变亮度
*
* @param percent
*/
private void onBrightnessSlide(float percent) {
if (mBrightness < 0) {
mBrightness = activity.getWindow().getAttributes().screenBrightness;
if (mBrightness <= 0.00f)
mBrightness = 0.50f;
if (mBrightness < 0.01f)
mBrightness = 0.01f;
// 显示
mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
mOperationTv.setVisibility(VISIBLE);
}
WindowManager.LayoutParams lpa = activity.getWindow().getAttributes();
lpa.screenBrightness = mBrightness + percent;
if (lpa.screenBrightness > 1.0f)
lpa.screenBrightness = 1.0f;
else if (lpa.screenBrightness < 0.01f)
lpa.screenBrightness = 0.01f;
activity.getWindow().setAttributes(lpa);
mOperationTv.setText((int) (lpa.screenBrightness * 100) + "%");
if (lpa.screenBrightness * 100 >= 90) {
mOperationBg.setImageResource(R.drawable.light_100);
} else if (lpa.screenBrightness * 100 >= 80 && lpa.screenBrightness * 100 < 90) {
mOperationBg.setImageResource(R.drawable.light_90);
} else if (lpa.screenBrightness * 100 >= 70 && lpa.screenBrightness * 100 < 80) {
mOperationBg.setImageResource(R.drawable.light_80);
} else if (lpa.screenBrightness * 100 >= 60 && lpa.screenBrightness * 100 < 70) {
mOperationBg.setImageResource(R.drawable.light_70);
} else if (lpa.screenBrightness * 100 >= 50 && lpa.screenBrightness * 100 < 60) {
mOperationBg.setImageResource(R.drawable.light_60);
} else if (lpa.screenBrightness * 100 >= 40 && lpa.screenBrightness * 100 < 50) {
mOperationBg.setImageResource(R.drawable.light_50);
} else if (lpa.screenBrightness * 100 >= 30 && lpa.screenBrightness * 100 < 40) {
mOperationBg.setImageResource(R.drawable.light_40);
} else if (lpa.screenBrightness * 100 >= 20 && lpa.screenBrightness * 100 < 20) {
mOperationBg.setImageResource(R.drawable.light_30);
} else if (lpa.screenBrightness * 100 >= 10 && lpa.screenBrightness * 100 < 20) {
mOperationBg.setImageResource(R.drawable.light_20);
}
}
/**
* 设置视频文件名
*
* @param name
*/
public void setVideoName(String name) {
videoname = name;
if (mFileName != null) {
mFileName.setText(name);
}
}
/**
* 隐藏或显示
*/
private void toggleMediaControlsVisiblity() {
if (isShowing()) {
hide();
} else {
show();
}
}
/**
* 播放/暂停
*/
private void playOrPause() {
if (videoView != null)
if (videoView.isPlaying()) {
videoView.pause();
} else {
videoView.start();
}
}
}
自定义控制器布局文件:mymediacontroller.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="@drawable/video_player_bg_color"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#77000000"
android:layout_height="34dp">
<ImageButton
android:id="@+id/mediacontroller_top_back"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="@null"
android:src="@drawable/ic_player_close_white"/>
<TextView
android:id="@+id/mediacontroller_filename"
style="@style/MediaController_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/mediacontroller_top_back"
android:ellipsize="marquee"
android:singleLine="true"
android:text="file name"/>
<ImageButton
android:id="@+id/mediacontroller_share"
android:layout_width="50dp"
android:layout_height="match_parent"
android:background="@null"
android:src="@drawable/ic_action_share_without_padding"
android:layout_alignParentRight="true"/>
<ImageButton
android:id="@+id/mediacontroller_favorite"
android:layout_width="50dp"
android:layout_height="match_parent"
android:background="@null"
android:layout_toLeftOf="@id/mediacontroller_share"
android:src="@drawable/ic_action_favorites"/>
</RelativeLayout>
<ImageButton
android:id="@+id/mediacontroller_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/paly_selector"
android:background="@null"/>
<RelativeLayout
android:id="@+id/operation_volume_brightness"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
android:background="@drawable/videobg"
android:orientation="horizontal"
android:padding="0dip"
android:visibility="gone">
<ImageView
android:id="@+id/operation_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/video_volumn_bg"/>
<TextView
android:id="@+id/operation_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/operation_bg"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom ="true"
android:text="32:22/45:00"
android:textColor="#ffffff"
android:textSize="10sp"
android:visibility="gone"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:background="#77000000"
android:layout_height="50dp">
<TextView
android:id="@+id/mediacontroller_time_current"
style="@style/MediaController_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:text="33:33:33"
/>
<TextView
android:id="@+id/mediacontroller_time_total"
style="@style/MediaController_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:text="33:33:33"/>
<ImageView
android:id="@+id/mediacontroller_scale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_action_scale" />
<SeekBar
android:id="@+id/mediacontroller_seekbar"
style="@style/MediaController_SeekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/mediacontroller_time_total"
android:layout_toRightOf="@id/mediacontroller_time_current"
android:focusable="true"
android:max="1000"/>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
MainActivity布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="retrofit.mifeng.us.myvitamio.MainActivity">
<io.vov.vitamio.widget.CenterLayout
android:id="@+id/cl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<io.vov.vitamio.widget.VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vv"/>
</io.vov.vitamio.widget.CenterLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerInParent="true">
//缓冲进度百分比
<TextView
android:id="@+id/buffer_percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:textColor="#e6ff01"/>
//缓冲网速
<TextView
android:id="@+id/net_speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:textColor="#04fa00"/>
</LinearLayout>
</RelativeLayout>
SPUtils轻量级存储工具类:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by 21903 on 2017/6/30.
*/
public class SPUtils {
private String name="jianbao";
/*
* 保存数据的方法
* */
public void saveShared(String key,long value,Context ctx){
SharedPreferences shared=ctx.getSharedPreferences(name,0);
SharedPreferences.Editor edit = shared.edit();
edit.putLong(key, value);
edit.commit();
}
/*
* 从本地获取数据
* */
public long getShared(Context ctx,String key){
SharedPreferences shared = ctx.getSharedPreferences(name, 0);
long aLong = shared.getLong(key, 0);
return aLong;
}
}
android 清单文件配置 屏幕横竖切换不影响生命周期(添加android:configChanges=”keyboardHidden|orientation|screenSize”)
<activity android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>