完善VideoPlayerActivity
<span style="font-size:18px;">public class VideoPlayerActivity extends BaseActivity {
private static final int MSG_UPDATE_SYSTEM_TIME = 0;
private static final int MSG_UPDATE_POSITION = 1;
private static final int MSG_HIDE_CONTROLLOR = 2;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MSG_UPDATE_SYSTEM_TIME:
startUpdateSystemTime();
break;
case MSG_UPDATE_POSITION:
startUpdatePosition();
break;
case MSG_HIDE_CONTROLLOR:
hideControllor();
break;
}
}
};
private VideoView videoView;
private ImageView iv_pause;
private TextView tv_title;
private VideoReceiver videoReceiver;
private ImageView iv_battery;
private TextView tv_system_time;
private ImageView iv_mute;
private SeekBar sk_volume;
private AudioManager mAudioManager;
private int mCurrentVolume;
private float mStartY;
private int mStartVolume;
private View alpha_cover;
private float mStartAlpha;
private TextView tv_position;
private SeekBar sk_position;
private TextView tv_duration;
private ImageView iv_pre;
private ImageView iv_next;
private ArrayList<VideoItem> mVideoItems;
private int mPosition;
private LinearLayout ll_top;
private LinearLayout ll_bottom;
private GestureDetector gestureDetector;
// 如果为true,则说明面板是显示状态
private boolean isContollorShowing = false;
private ImageView iv_fullscreen;
private LinearLayout ll_loading_cover;
private ProgressBar pb_buffering;
@Override
protected int getLayoutId() {
return R.layout.activity_video_player;
}
@Override
protected void initView() {
videoView = (VideoView) findViewById(R.id.videoview);
alpha_cover = findViewById(R.id.video_alpha_cover);
ll_top = (LinearLayout) findViewById(R.id.video_ll_top);
ll_bottom = (LinearLayout) findViewById(R.id.video_ll_bottom);
ll_loading_cover = (LinearLayout) findViewById(R.id.video_ll_loading_cover);
pb_buffering = (ProgressBar) findViewById(R.id.video_pb_buffering);
// 顶部面板
tv_title = (TextView) findViewById(R.id.video_tv_title);
iv_battery = (ImageView) findViewById(R.id.video_iv_battery);
tv_system_time = (TextView) findViewById(R.id.video_tv_system_time);
iv_mute = (ImageView) findViewById(R.id.video_iv_mute);
sk_volume = (SeekBar) findViewById(R.id.video_sk_volume);
// 底部面板
iv_pause = (ImageView) findViewById(R.id.video_iv_pause);
tv_position = (TextView) findViewById(R.id.video_tv_position);
sk_position = (SeekBar) findViewById(R.id.video_sk_position);
tv_duration = (TextView) findViewById(R.id.video_tv_duration);
iv_pre = (ImageView) findViewById(R.id.video_iv_pre);
iv_next = (ImageView) findViewById(R.id.video_iv_next);
iv_fullscreen = (ImageView) findViewById(R.id.video_iv_fullscreen);
}
@Override
protected void initListener() {
// 顶部面板
iv_mute.setOnClickListener(this);
// 底部面板
iv_pause.setOnClickListener(this);
iv_pre.setOnClickListener(this);
iv_next.setOnClickListener(this);
iv_fullscreen.setOnClickListener(this);
// 进度条监听
OnVideoSeekBarChangeListener onSeekBarChangeListener = new OnVideoSeekBarChangeListener();
sk_volume.setOnSeekBarChangeListener(onSeekBarChangeListener);
sk_position.setOnSeekBarChangeListener(onSeekBarChangeListener);
// 注册手势监听
gestureDetector = new GestureDetector(this, new OnVideoGestureListener());
// 视频相关的监听
videoView.setOnPreparedListener(new OnVideoPreparedListener());
videoView.setBufferingUpdateListener(new OnVideoBufferingUpdateListener());//视频缓存更新监听
videoView.setOnInfoListener(new OnVideoInfoListener());//视频播放中的监听
videoView.setOnErrorListener(new OnVideoErrorListener());
// 注册广播
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
videoReceiver = new VideoReceiver();
registerReceiver(videoReceiver, filter);
}
@Override
protected void initData() {
// 获取数据
Uri uri = getIntent().getData();
if (uri!=null){
// 从外部打开
videoView.setVideoURI(uri);
iv_pre.setEnabled(false);
iv_next.setEnabled(false);
// file:///storage/emulated/0/Download/video/oppo - 2.mp4
// schema://host:port/path
tv_title.setText(uri.getPath());
}else {
// 从应用内打开
mVideoItems = (ArrayList<VideoItem>) getIntent().getSerializableExtra("videoItems");
mPosition = getIntent().getIntExtra("position",-1);
// 可用性验证
if (mVideoItems.size()==0|| mPosition ==-1){
return;
}
// 播放视频
playItem();
}
// 开是更新系统时间
startUpdateSystemTime();
// 获取系统音量
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
sk_volume.setMax(maxVolume);
int currentVolume = getCurrentVolume();
logE("VideoPlayerActivity.initData,maxVolume="+maxVolume+";currentVoume="+currentVolume);
sk_volume.setProgress(currentVolume);
// 修改透明遮罩为完全透明
ViewCompat.setAlpha(alpha_cover,0);
// 隐藏控制面板
initHideControllor();
}
// 初始化界面时隐藏控制面板
private void initHideControllor() {
// 使用 measure 来获取控件的高度
ll_top.measure(0,0);
ViewCompat.animate(ll_top).translationY(-ll_top.getMeasuredHeight()).setDuration(2000).start();
// logE("VideoPlayerActivity.initHideControllor,topH="+ll_top.getHeight()+";mH="+ll_top.getMeasuredHeight());
// 使用布局监听来获取控件高度
ll_bottom.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ll_bottom.getViewTreeObserver().removeGlobalOnLayoutListener(this);
logE("VideoPlayerActivity.onGlobalLayout,bottomH="+ll_bottom.getHeight());
ViewCompat.animate(ll_bottom).translationY(ll_bottom.getHeight()).setDuration(2000).start();
}
});
isContollorShowing = false;
}
// 获取当前 mPosition 指定的视频,并开始播放
private void playItem() {
// 获取要播放的视频
VideoItem videoItem = mVideoItems.get(mPosition);
// VideoItem videoItem = (VideoItem) getIntent().getSerializableExtra("videoItem");
logE("VideoPlayerActivity.initData,item="+videoItem);
// 播放视频
videoView.setVideoPath(videoItem.getPath());
// 更新标题
tv_title.setText(videoItem.getTitle());
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(videoReceiver);
mHandler.removeCallbacksAndMessages(null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 由手势分析器,先分析触摸事件
gestureDetector.onTouchEvent(event);
// 最终音量 = 起始音量 + 变化音量
// 变化音量 = 划过屏幕的百分比 * 最大音量
// 划过屏幕的百分比 = 划过屏幕的距离 / 屏幕的高度
// 划过屏幕的距离 = 手指的当前位置 - 手指的起始位置
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
// 手指的起始位置
mStartY = event.getY();
// 起始音量
mStartVolume = getCurrentVolume();
// 起始透明度
mStartAlpha = ViewCompat.getAlpha(alpha_cover);
break;
case MotionEvent.ACTION_MOVE:
// 手指的当前位置
float currentY = event.getY();
// 划过屏幕的距离
float distance = currentY - mStartY;
// 屏幕的高度0
int halfScreenH = getWindowManager().getDefaultDisplay().getHeight() / 2;
int halfScreenW = getWindowManager().getDefaultDisplay().getWidth() / 2;
// 划过屏幕的百分比
float movePercent = distance / halfScreenH;
if (event.getX()< halfScreenW) {
// 左侧,修改亮度
moveAlpha(movePercent);
}else {
// 右侧,修改音量
moveVolume(movePercent);
}
break;
}
return true;
}
// 根据手指划过屏幕的百分比,修改屏幕亮度
private void moveAlpha(float movePercent) {
// 最终透明度 = 起始透明度 + 划过屏幕的百分比
float finalAlpha = mStartAlpha + movePercent;
// logE("VideoPlayerActivity.moveAlpha,mStartAlpha="+mStartAlpha+":movePercent="+movePercent+";finalAlpha="+finalAlpha);
if (finalAlpha>=0&&finalAlpha<=1){
// 只有在 0-1范围内才允许修改透明度
ViewCompat.setAlpha(alpha_cover,finalAlpha);
}
}
// 根据手指划过屏幕的百分比修改系统音量
private void moveVolume(float movePercent) {
// 变化音量
float offsetVolume = movePercent * sk_volume.getMax();
// 最终音量
int finalVolume = (int) (mStartVolume + offsetVolume);
// 更新音量
setVolume(finalVolume);
}
@Override
protected void processClick(View v) {
switch (v.getId()){
case R.id.video_iv_pause:
switchPauseStatus();
break;
case R.id.video_iv_mute:
switchMuteStatus();
break;
case R.id.video_iv_pre:
playPre();
break;
case R.id.video_iv_next:
playNext();
break;
case R.id.video_iv_fullscreen:
switchFullScreen();
break;
}
}
// 切换全屏状态
private void switchFullScreen() {
videoView.switchFullScreen();
updateFullScreenBtn();
}
// 更新全屏按钮使用的图片
private void updateFullScreenBtn() {
if (videoView.isFullScreen()){
// 全屏
iv_fullscreen.setImageResource(R.drawable.video_defaultscreen_selector);
}else{
// 非全屏
iv_fullscreen.setImageResource(R.drawable.video_fullscreen_selector);
}
}
// 播放上一曲
private void playPre() {
if (mPosition!=0){
mPosition--;
playItem();
}
updatePreAndNext();
}
// 播放下一曲
private void playNext() {
if (mPosition!=mVideoItems.size()-1){
mPosition++;
playItem();
}
updatePreAndNext();
}
// 更新上一曲和下一曲的可用性
private void updatePreAndNext() {
iv_pre.setEnabled(mPosition!=0);
iv_next.setEnabled(mPosition!=mVideoItems.size()-1);
}
// 如果当前音量不为0,则记录当前音量,并将音量置为0;否则将音量还原为之前的音量
private void switchMuteStatus() {
if (getCurrentVolume() !=0){
// 非静音状态
mCurrentVolume = getCurrentVolume();
setVolume(0);
}else{
// 静音状态
setVolume(mCurrentVolume);
}
}
// 更新音量
private void setVolume(int volume) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,volume,0);
sk_volume.setProgress(volume);
}
// 获取音量
private int getCurrentVolume() {
return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
// 更新系统时间,并隔一段时间后再次更新
private void startUpdateSystemTime() {
// logE("VideoPlayerActivity.startUpdateSystemTime,time="+System.currentTimeMillis());
tv_system_time.setText(StringUtils.formatSystemTime());
// 发送延迟消息
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_SYSTEM_TIME,500);
}
// 切换暂停/播放状态
private void switchPauseStatus() {
if (videoView.isPlaying()){
// 播放状态,需要暂停
videoView.pause();
mHandler.removeMessages(MSG_UPDATE_POSITION);
}else {
// 暂停状态,需要开启播放
videoView.start();
startUpdatePosition();
}
updatePauseBtn();
}
// 更新暂停按钮使用的图片
private void updatePauseBtn() {
if (videoView.isPlaying()){
// 播放状态
iv_pause.setImageResource(R.drawable.video_pause_selector);
}else {
// 暂停状态
iv_pause.setImageResource(R.drawable.video_play_selector);
}
}
// 根据当前系统的电量,更新电池图片
private void updateBatteryBtn(int level) {
if (level < 10) {
iv_battery.setImageResource(R.mipmap.ic_battery_0);
} else if (level < 20) {
iv_battery.setImageResource(R.mipmap.ic_battery_10);
} else if (level < 40) {
iv_battery.setImageResource(R.mipmap.ic_battery_20);
} else if (level < 60) {
iv_battery.setImageResource(R.mipmap.ic_battery_40);
} else if (level < 80) {
iv_battery.setImageResource(R.mipmap.ic_battery_60);
} else if (level < 100) {
iv_battery.setImageResource(R.mipmap.ic_battery_80);
} else {
iv_battery.setImageResource(R.mipmap.ic_battery_100);
}
}
// 更新播放进度,并稍后再次更新
private void startUpdatePosition() {
int position = videoView.getCurrentPosition();// 获取当前播放位置
updatePosition(position);
// 发送延迟消息
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_POSITION,500);
}
// 刚更新播放进度为position
private void updatePosition(int position) {
// logE("VideoPlayerActivity.updatePosition,position="+position+";duration="+videoView.getDuration());
tv_position.setText(StringUtils.formatTime(position));
sk_position.setProgress(position);
}
// 显示控制面板
private void showContollor() {
ViewCompat.animate(ll_top).translationY(0).setDuration(500).start();
ViewCompat.animate(ll_bottom).translationY(0).setDuration(500).start();
isContollorShowing = true;
}
// 隐藏控制面板
private void hideControllor() {
ViewCompat.animate(ll_top).translationY(-ll_top.getHeight()).setDuration(500).start();
ViewCompat.animate(ll_bottom).translationY(ll_bottom.getHeight()).setDuration(500).start();
isContollorShowing = false;
}
private class OnVideoPreparedListener implements MediaPlayer.OnPreparedListener {
@Override
// 视频资源已经加载完毕
public void onPrepared(MediaPlayer mp) {
// 隐藏加载遮罩
ll_loading_cover.setVisibility(View.GONE);
// 开启播放
videoView.start();
// videoView.setMediaController(new MediaController(this));
// 更新暂停按钮
updatePauseBtn();
// 初始化进度信息
int duration = videoView.getDuration();// 获取总时长
tv_duration.setText(StringUtils.formatTime(duration));
sk_position.setMax(duration);
startUpdatePosition();
}
}
//主要用来接收电量的变化
private class VideoReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)){
// 获取到电量变化
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
// logE("VideoReceiver.onReceive,level="+level);
updateBatteryBtn(level);
}
}
}
//进度条监听
private class OnVideoSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
@Override
// 当进度发生变化的时候被调用
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// logE("OnVideoSeekBarChangeListener.onProgressChanged,progress="+progress+";fromUser="+fromUser);
// 如果不是用户发起的变更,则不处理
if (!fromUser){
return;
}
switch (seekBar.getId()){//音量进度条
case R.id.video_sk_volume:
// 修改系统音量
// 参数二 要设置的音量大小
// 参数三 如果为1 则会显示系统的音量控制条,如果为0则不显示
setVolume(progress);
break;
case R.id.video_sk_position://播放进度进度条
// 跳转播放进度
videoView.seekTo(progress);
break;
}
}
@Override
// 当用户按下的时候被调用
public void onStartTrackingTouch(SeekBar seekBar) {
logE("OnVideoSeekBarChangeListener.onStartTrackingTouch,");
mHandler.removeMessages(MSG_HIDE_CONTROLLOR);
}
@Override
// 当用户松手时被调用
public void onStopTrackingTouch(SeekBar seekBar) {
logE("OnVideoSeekBarChangeListener.onStopTrackingTouch,");
mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLOR,5000);
}
}
private class OnVideoCompletionListener implements MediaPlayer.OnCompletionListener {
@Override
// 视频播放结束
public void onCompletion(MediaPlayer mp) {
// 由于低版本的MediaPlayer存在BUG,当视频播放结束后,有可能播放进度不完整,需要将进度强制的设置为总时长
mHandler.removeMessages(MSG_UPDATE_POSITION);
int duration = videoView.getDuration();
updatePosition(duration);
// 更新暂停按钮
// updatePauseBtn();
iv_pause.setImageResource(R.drawable.video_play_selector);
}
}
private class OnVideoGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {//单机监听
// logE("OnVideoGestureListener.onSingleTapConfirmed,");
if (isContollorShowing){
// 显示状态,需要将面板隐藏
hideControllor();
}else{
// 隐藏状态,需要将面板显示出来
showContollor();
// 发送延迟消息,自动隐藏控制面板
mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLOR, 5000);
}
return super.onSingleTapConfirmed(e);
}
@Override
public boolean onDoubleTap(MotionEvent e) {//双击监听
// logE("OnVideoGestureListener.onDoubleTap,");
switchFullScreen();
return super.onDoubleTap(e);
}
@Override
public void onLongPress(MotionEvent e) {//长按监听
super.onLongPress(e);
switchPauseStatus();
}
}
//视频缓存更新监听
private class OnVideoBufferingUpdateListener implements MediaPlayer.OnBufferingUpdateListener {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// logE("OnVideoBufferingUpdateListener.onBufferingUpdate,percent="+percent);
float bufferPercent = percent / 100f;
int position = (int) (sk_position.getMax() * bufferPercent);
sk_position.setSecondaryProgress(position);//设置缓存进度
}
}
private class OnVideoInfoListener implements MediaPlayer.OnInfoListener {
@Override
// 播放过程中发生了一些状态变化
public boolean onInfo(MediaPlayer mp, int what, int extra) {
switch (what){
case MediaPlayer.MEDIA_INFO_BUFFERING_START://缓冲开始
// 播放中出现缓冲
pb_buffering.setVisibility(View.VISIBLE);
break;
case MediaPlayer.MEDIA_INFO_BUFFERING_END://缓冲结束
// 播放中缓冲结束
pb_buffering.setVisibility(View.GONE);
break;
}
return false;
}
}
private class OnVideoErrorListener implements MediaPlayer.OnErrorListener {
@Override
// 发生了不可修复的错误
public boolean onError(MediaPlayer mp, int what, int extra) {
AlertDialog .Builder builder = new AlertDialog.Builder(VideoPlayerActivity.this);
builder.setTitle("警告")
.setMessage("该视频无法播放")
.setPositiveButton("退出界面", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
return false;
}
}
}</span>
重写了系统的videoView
解决了全屏问题
public class VideoView extends SurfaceView implements MediaPlayerControl {
private String TAG = "VideoView";
// settable by the client
private Uri mUri;
private Map<String, String> mHeaders;
// all possible internal states
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
// mCurrentState is a VideoView object's current state.
// mTargetState is the state that a method caller intends to reach.
// For instance, regardless the VideoView object's current state,
// calling pause() intends to bring the object to a target state
// of STATE_PAUSED.
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
// All the stuff we need for playing and showing a video
private SurfaceHolder mSurfaceHolder = null;
private MediaPlayer mMediaPlayer = null;
private int mAudioSession;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private MediaController mMediaController;
private OnCompletionListener mOnCompletionListener;
private MediaPlayer.OnPreparedListener mOnPreparedListener;
private int mCurrentBufferPercentage;
private OnErrorListener mOnErrorListener;
private OnInfoListener mOnInfoListener;
private int mSeekWhenPrepared; // recording the seek position while preparing
private boolean mCanPause;
private boolean mCanSeekBack;
private boolean mCanSeekForward;
private Context mContext;
private int mScreenH;
private int mScreenW;
private int mDefaultH;
private int mDefaultW;
// 如果为true,则说明当前是全屏状态
private boolean isFullScreen = false;
public VideoView(Context context) {
super(context);
initVideoView(context);
}
public VideoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
initVideoView(context);
}
public VideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initVideoView(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Log.i("@@@@", "onMeasure(" + MeasureSpec.toString(widthMeasureSpec) + ", "
// + MeasureSpec.toString(heightMeasureSpec) + ")");
int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
if (mVideoWidth > 0 && mVideoHeight > 0) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) {
// the size is fixed
width = widthSpecSize;
height = heightSpecSize;
// for compatibility, we adjust size based on aspect ratio
if ( mVideoWidth * height < width * mVideoHeight ) {
//Log.i("@@@", "image too wide, correcting");
width = height * mVideoWidth / mVideoHeight;
} else if ( mVideoWidth * height > width * mVideoHeight ) {
//Log.i("@@@", "image too tall, correcting");
height = width * mVideoHeight / mVideoWidth;
}
} else if (widthSpecMode == MeasureSpec.EXACTLY) {
// only the width is fixed, adjust the height to match aspect ratio if possible
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) {
// couldn't match aspect ratio within the constraints
height = heightSpecSize;
}
} else if (heightSpecMode == MeasureSpec.EXACTLY) {
// only the height is fixed, adjust the width to match aspect ratio if possible
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) {
// couldn't match aspect ratio within the constraints
width = widthSpecSize;
}
} else {
// neither the width nor the height are fixed, try to use actual video size
width = mVideoWidth;
height = mVideoHeight;
if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) {
// too tall, decrease both width and height
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
}
if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) {
// too wide, decrease both width and height
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
}
}
} else {
// no size yet, just adopt the given spec sizes
}
setMeasuredDimension(width, height);
mDefaultH = height;
mDefaultW = width;
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(VideoView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
info.setClassName(VideoView.class.getName());
}
}
public int resolveAdjustedSize(int desiredSize, int measureSpec) {
return getDefaultSize(desiredSize, measureSpec);
}
private void initVideoView(Context context) {
mVideoWidth = 0;
mVideoHeight = 0;
getHolder().addCallback(mSHCallback);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
mContext = context;
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mScreenH = windowManager.getDefaultDisplay().getHeight();
mScreenW = windowManager.getDefaultDisplay().getWidth();
}
public void setVideoPath(String path) {
setVideoURI(Uri.parse(path));
}
public void setVideoURI(Uri uri) {
setVideoURI(uri, null);
}
/**
* @hide
*/
public void setVideoURI(Uri uri, Map<String, String> headers) {
mUri = uri;
mHeaders = headers;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
}
private void openVideo() {
if (mUri == null || mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the framework.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mContext.sendBroadcast(i);
// we shouldn't clear the target state, because somebody might have
// called start() previously
release(false);
try {
mMediaPlayer = new MediaPlayer();
if (mAudioSession != 0) {
mMediaPlayer.setAudioSessionId(mAudioSession);
} else {
mAudioSession = mMediaPlayer.getAudioSessionId();
}
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnInfoListener(mOnInfoListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
mMediaPlayer.setDataSource(mContext, mUri/*, mHeaders*/);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
// we don't set the target state here either, but preserve the
// target state that was there before.
mCurrentState = STATE_PREPARING;
attachMediaController();
} catch (IOException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
}
}
public void setMediaController(MediaController controller) {
if (mMediaController != null) {
mMediaController.hide();
}
mMediaController = controller;
attachMediaController();
}
private void attachMediaController() {
if (mMediaPlayer != null && mMediaController != null) {
mMediaController.setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ?
(View)this.getParent() : this;
mMediaController.setAnchorView(anchorView);
mMediaController.setEnabled(isInPlaybackState());
}
}
MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener =
new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if (mVideoWidth != 0 && mVideoHeight != 0) {
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
requestLayout();
}
}
};
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mCurrentState = STATE_PREPARED;
// Get the capabilities of the player for this stream
// Metadata data = mp.getMetadata(MediaPlayer.METADATA_ALL,
// MediaPlayer.BYPASS_METADATA_FILTER);
//
// if (data != null) {
// mCanPause = !data.has(Metadata.PAUSE_AVAILABLE)
// || data.getBoolean(Metadata.PAUSE_AVAILABLE);
// mCanSeekBack = !data.has(Metadata.SEEK_BACKWARD_AVAILABLE)
// || data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE);
// mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
// || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
// } else {
mCanPause = mCanSeekBack = mCanSeekForward = true;
// }
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer);
}
if (mMediaController != null) {
mMediaController.setEnabled(true);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
//Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
if (mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
// We didn't actually change the size (it was already at the size
// we need), so we won't get a "surface changed" callback, so
// start the video here instead of in the callback.
if (mTargetState == STATE_PLAYING) {
start();
if (mMediaController != null) {
mMediaController.show();
}
} else if (!isPlaying() &&
(seekToPosition != 0 || getCurrentPosition() > 0)) {
if (mMediaController != null) {
// Show the media controls when we're paused into a video and make 'em stick.
mMediaController.show(0);
}
}
}
} else {
// We don't know the video size yet, but should start anyway.
// The video size might be reported to us later.
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private OnCompletionListener mCompletionListener =
new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mMediaController != null) {
mMediaController.hide();
}
if (mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private OnErrorListener mErrorListener =
new OnErrorListener() {
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mMediaController != null) {
mMediaController.hide();
}
/* If an error handler has been supplied, use it and finish. */
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
/* Otherwise, pop up an error dialog so the user knows that
* something bad has happened. Only try and pop up the dialog
* if we're attached to a window. When we're going away and no
* longer have a window, don't bother showing the user an error.
*/
// if (getWindowToken() != null) {
// Resources r = mContext.getResources();
// int messageId;
//
// if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
// messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback;
// } else {
// messageId = com.android.internal.R.string.VideoView_error_text_unknown;
// }
//
// new AlertDialog.Builder(mContext)
// .setMessage(messageId)
// .setPositiveButton(com.android.internal.R.string.VideoView_error_button,
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// /* If we get here, there is no onError listener, so
// * at least inform them that the video is over.
// */
// if (mOnCompletionListener != null) {
// mOnCompletionListener.onCompletion(mMediaPlayer);
// }
// }
// })
// .setCancelable(false)
// .show();
// }
return true;
}
};
// private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
// new MediaPlayer.OnBufferingUpdateListener() {
// public void onBufferingUpdate(MediaPlayer mp, int percent) {
// mCurrentBufferPercentage = percent;
// }
// };
private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener ;
public void setBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener bufferingUpdateListener) {
this.mBufferingUpdateListener = bufferingUpdateListener;
}
/**
* Register a callback to be invoked when the media file
* is loaded and ready to go.
*
* @param l The callback that will be run
*/
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l)
{
mOnPreparedListener = l;
}
/**
* Register a callback to be invoked when the end of a media file
* has been reached during playback.
*
* @param l The callback that will be run
*/
public void setOnCompletionListener(OnCompletionListener l)
{
mOnCompletionListener = l;
}
/**
* Register a callback to be invoked when an error occurs
* during playback or setup. If no listener is specified,
* or if the listener returned false, VideoView will inform
* the user of any errors.
*
* @param l The callback that will be run
*/
public void setOnErrorListener(OnErrorListener l)
{
mOnErrorListener = l;
}
/**
* Register a callback to be invoked when an informational event
* occurs during playback or setup.
*
* @param l The callback that will be run
*/
public void setOnInfoListener(OnInfoListener l) {
mOnInfoListener = l;
}
SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format,
int w, int h)
{
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
public void surfaceCreated(SurfaceHolder holder)
{
mSurfaceHolder = holder;
openVideo();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
// after we return from this we can't use the surface any more
mSurfaceHolder = null;
if (mMediaController != null) mMediaController.hide();
release(true);
}
};
/*
* release the media player in any state
*/
private void release(boolean cleartargetstate) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (cleartargetstate) {
mTargetState = STATE_IDLE;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (isInPlaybackState() && mMediaController != null) {
toggleMediaControlsVisiblity();
}
return false;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
if (isInPlaybackState() && mMediaController != null) {
toggleMediaControlsVisiblity();
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK &&
keyCode != KeyEvent.KEYCODE_VOLUME_UP &&
keyCode != KeyEvent.KEYCODE_VOLUME_DOWN &&
keyCode != KeyEvent.KEYCODE_VOLUME_MUTE &&
keyCode != KeyEvent.KEYCODE_MENU &&
keyCode != KeyEvent.KEYCODE_CALL &&
keyCode != KeyEvent.KEYCODE_ENDCALL;
if (isInPlaybackState() && isKeyCodeSupported && mMediaController != null) {
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
if (mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
} else {
start();
mMediaController.hide();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if (!mMediaPlayer.isPlaying()) {
start();
mMediaController.hide();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
if (mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
}
return true;
} else {
toggleMediaControlsVisiblity();
}
}
return super.onKeyDown(keyCode, event);
}
private void toggleMediaControlsVisiblity() {
if (mMediaController.isShowing()) {
mMediaController.hide();
} else {
mMediaController.show();
}
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
}
}
mTargetState = STATE_PAUSED;
}
public void suspend() {
release(false);
}
public void resume() {
openVideo();
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
return mMediaPlayer.getDuration();
}
return -1;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null &&
mCurrentState != STATE_ERROR &&
mCurrentState != STATE_IDLE &&
mCurrentState != STATE_PREPARING);
}
@Override
public boolean canPause() {
return mCanPause;
}
@Override
public boolean canSeekBackward() {
return mCanSeekBack;
}
@Override
public boolean canSeekForward() {
return mCanSeekForward;
}
@Override
public int getAudioSessionId() {
if (mAudioSession == 0) {
MediaPlayer foo = new MediaPlayer();
mAudioSession = foo.getAudioSessionId();
foo.release();
}
return mAudioSession;
}
// 切换全屏状态
public void switchFullScreen(){
if (isFullScreen){
// 全屏,需要切换到默认大小
getLayoutParams().width = mDefaultW;
getLayoutParams().height = mDefaultH;
}else{
// 非全屏,需要切换到全屏大小
getLayoutParams().width = mScreenW;
getLayoutParams().height = mScreenH;
}
requestLayout();
isFullScreen = !isFullScreen;
}
// 返回当前的全屏状态
// 返回true则说明当前是全屏状态
public boolean isFullScreen() {
return isFullScreen;
}
}
布局文件
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.itcast.mobileplayer91.ui.activity.VideoPlayerActivity">
<!--视频播放控件-->
<com.itcast.mobileplayer91.view.VideoView
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
<!--顶部面板-->
<include layout="@layout/activity_video_player_top" />
<!--底部面板-->
<include
layout="@layout/activity_video_player_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
<!--亮度遮罩-->
<View
android:id="@+id/video_alpha_cover"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e000" />
<!--加载遮罩-->
<LinearLayout
android:id="@+id/video_ll_loading_cover"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_player_loading_background"
android:gravity="center"
android:orientation="horizontal">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="正在加载中..."
android:textColor="@color/white"
android:textSize="20sp" />
</LinearLayout>
<!--缓冲提示-->
<ProgressBar
android:id="@+id/video_pb_buffering"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
顶部布局 activity_video_player_top.xml
底部布局 activity_video_player_bottom.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/video_ll_top" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--系统信息栏--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_video_system_status" android:gravity="center_vertical" android:padding="6dp"> <!--标题--> <TextView android:id="@+id/video_tv_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="文件名" android:textColor="@color/white" android:textSize="18sp" /> <!--系统电量--> <ImageView android:id="@+id/video_iv_battery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="6dp" android:layout_marginRight="6dp" android:src="@mipmap/ic_battery_40" /> <!--系统时间--> <TextView android:id="@+id/video_tv_system_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="系统时间" android:textColor="@color/white" android:textSize="18sp" /> </LinearLayout> <!--音量控制条--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_video_volume_control" android:gravity="center_vertical" android:orientation="horizontal" android:padding="6dp"> <!--静音--> <ImageView android:id="@+id/video_iv_mute" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/video_mute_selector" /> <!--音量控制条--> <SeekBar android:id="@+id/video_sk_volume" style="@android:style/Widget.SeekBar" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:maxHeight="10dp" android:minHeight="10dp" android:progress="40" android:progressDrawable="@drawable/video_seekbar_drawable" android:thumb="@drawable/video_progress_thumb" android:thumbOffset="0dp" /> </LinearLayout> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/video_ll_bottom" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--播放进度--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_video_duration_control" android:gravity="center_vertical" android:orientation="horizontal" android:padding="6dp"> <!--已播放时间--> <TextView android:id="@+id/video_tv_position" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="00:00" android:textColor="@color/white" android:textSize="18sp" /> <!--播放进度条--> <SeekBar android:id="@+id/video_sk_position" style="@android:style/Widget.SeekBar" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="6dp" android:layout_marginRight="6dp" android:layout_weight="1" android:maxHeight="10dp" android:minHeight="10dp" android:progress="40" android:secondaryProgress="80" android:progressDrawable="@drawable/video_seekbar_drawable" android:thumb="@drawable/video_progress_thumb" android:thumbOffset="0dp" /> <!--视频总时长--> <TextView android:id="@+id/video_tv_duration" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="00:00" android:textColor="@color/white" android:textSize="18sp" /> </LinearLayout> <!--控制按钮--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_video_bottom_control" android:orientation="horizontal"> <ImageView android:id="@id/back" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/video_back_selector" /> <ImageView android:id="@+id/video_iv_pre" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/video_pre_selector" /> <ImageView android:id="@+id/video_iv_pause" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/video_play_selector" /> <ImageView android:id="@+id/video_iv_next" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/video_next_selector" /> <ImageView android:id="@+id/video_iv_fullscreen" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/video_fullscreen_selector" /> </LinearLayout> </LinearLayout>
从文件管理器打开视频时提示从我们写的播放器中播放
在清单文件中配置下videoPlayerActivity
<activity
android:name=".ui.activity.VideoPlayerActivity"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="rtsp" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="video/*" />
<data android:mimeType="application/sdp" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:mimeType="video/mpeg4" />
<data android:mimeType="video/mp4" />
<data android:mimeType="video/3gp" />
<data android:mimeType="video/3gpp" />
<data android:mimeType="video/3gpp2" />
</intent-filter>
</activity>
播放网络视频
<span style="font-size:18px;">public void click(View v){</span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>Intent intent = new Intent(Intent.ACTION_VIEW);
<span style="white-space:pre"> </span>intent.setDataAndType(Uri.parse("http://....mp4"),"video/MP4");
<span style="white-space:pre"> </span>startActivity(intent)
}</span>
将毫秒值转为时间格式的工具类
public class StringUtils {
// 格式化时间,01:02:03 或者 02:03
public static CharSequence formatTime(int duration){
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.add(Calendar.MILLISECOND,duration);
int hour = calendar.get(Calendar.HOUR);
if (hour < 1 ){
// 不足一小时 02:03
return DateFormat.format("mm:ss",duration);
}else{
// 超过一小时 01:02:03
return DateFormat.format("hh:mm:ss",duration);
}
}
// 将系统时间转换为 01:02:03
public static String formatSystemTime(){
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
return format.format(new Date());
}
// 将 beijingbeijing.mp3 --> beijinngbejing
public static String formatTitle(String title){
return title.substring(0,title.indexOf("."));
}
}