mediaplayer+surfaceview实现视频播放以及全屏窗口切换

  一.概述

  由于需求,要做一个视频播放demo并且能实现半屏与全屏互相切换的操作。网上看了很多,动不动就第三方框架的,感觉也没太大必要,于是自己试着写了个。
  1.1 效果如下:
       

  二.基本思路

 1.视频的半屏的播放,用mediaplayer+surfaceview来实现即可。
  2.按下全屏键,此时手机屏幕横屏,视频填充全屏播放
 3.全屏按返回键,或者后退操作,手机变成竖屏,视频半屏播放  

 所以,我们要横竖屏切换,activity的生命周期不重走。这是需要配置信息
  android:configChanges="orientation|screenSize"
 
            
                

                
            
        
 

 三.具体代码如下

 
package com.maxence.mediaplayer.demo;

import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {

	private boolean ISPLAYING=false;
	private   boolean ISFULLSCREEN = false;
	private Button btn_full_screen;
	private Button btn_play_video;
	private Button btn_video_back;
	private ProgressBar pb_progressbar;
	private FrameLayout fl_group;
	private SurfaceView mSurfaceView;
	private MediaPlayer mMediaPlayer;
	private String videoUrl="http://183.59.160.61:30001/PLTV/88888905/224/3221227505/index.m3u8";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getActionBar().hide();
			initView();
			initData();
	}

	private void initData() {
		
		mMediaPlayer = new MediaPlayer();
		mSurfaceView.setKeepScreenOn(true);
		mSurfaceView.getHolder().addCallback(mCallback);
		mHandler.sendMessageDelayed(mHandler.obtainMessage(100), 3000);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
				if(ISFULLSCREEN){   //全屏切换半屏  
					ISFULLSCREEN = false;
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 手动横屏
					RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
							dp2px(MainActivity.this, 200));
					fl_group.setLayoutParams(lp);
					return true;
				}
				break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);

	}
	
	/**
	 * dp2px  动态设置视频的宽高
	 * @param context
	 * @param dpValue
	 * @return
	 */
	 public static int dp2px(Context context, float dpValue) {
	        final float scale = context.getResources().getDisplayMetrics().density;

	        return (int) (dpValue * scale + 0.5f);
	    }
	
	 
	 /**
	  * 触摸屏幕 按键出现 
	  */
	public boolean onTouchEvent(android.view.MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			btn_video_back.setVisibility(View.VISIBLE);
			btn_play_video.setVisibility(View.VISIBLE);
			btn_full_screen.setVisibility(View.VISIBLE);
			mHandler.sendEmptyMessageDelayed(100, 3000);
			break;

		default:
			break;
		}
		return true;
	};
	
	SurfaceHolder.Callback mCallback = new SurfaceHolder.Callback(){

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			if (videoUrl != null || !"".equals(videoUrl)) {
				new Thread(){
					public void run() {
						
						playVideo();
					};
				}.start();
			}
		}
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			mMediaPlayer.setDisplay(holder);
		}
		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
				
				pb_progressbar.setVisibility(View.VISIBLE);
			}
		}
	};
	
	
	private void initView() {

		btn_full_screen = (Button) findViewById(R.id.btn_full_video);
		btn_play_video = (Button) findViewById(R.id.btn_play_video);
		btn_video_back = (Button) findViewById(R.id.btn_video_back);
		pb_progressbar = (ProgressBar) findViewById(R.id.pb_progressbar);
		fl_group = (FrameLayout) findViewById(R.id.fl_group);
		mSurfaceView = (SurfaceView) findViewById(R.id.sv_surfaceview_);
		
		btn_full_screen.setOnClickListener(this);
		btn_play_video.setOnClickListener(this);
		btn_video_back.setOnClickListener(this);
	}

	protected void playVideo() {
		
		try {
			mMediaPlayer.reset(); // 重置
			mMediaPlayer.setDataSource(videoUrl);
			  // 视频地址
			mMediaPlayer.setDisplay(mSurfaceView.getHolder()); // holder
			mMediaPlayer.setOnPreparedListener(new PreparedListener()); //
			
			mMediaPlayer.prepare();
		}catch (IOException e) {
					Log.e("918", e.toString());
				}
		
		
	}
	
	Handler mHandler=new Handler(){
		
		public void handleMessage(android.os.Message msg) {
		  	switch (msg.what) {
			case 100:    
				btn_full_screen.setVisibility(View.GONE);
				btn_play_video.setVisibility(View.GONE);
				btn_video_back.setVisibility(View.GONE);
				break;

			default:
				break;
			}
			 
		};
	};
	
	class PreparedListener implements OnPreparedListener {
		int postSize;
		@Override
		public void onPrepared(MediaPlayer mp) {
			Log.e("onPrepared", "----onPrepared");
			pb_progressbar.setVisibility(View.GONE); // 取消dialog
			btn_play_video.setBackgroundResource(R.drawable.icon_topause);
			if (mMediaPlayer != null) {
				ISPLAYING=true;
				mMediaPlayer.start(); // 播放
				mHandler.sendMessageDelayed(mHandler.obtainMessage(100), 3000);
			} else {
				return;
			}

		}
	}

	@Override
	public void onClick(View v) {
	   
		switch (v.getId()) {
		case R.id.btn_full_video:

			if (ISFULLSCREEN) { // 全屏转半屏

				ISFULLSCREEN = false;
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 手动横屏
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
						dp2px(MainActivity.this, 200));
				fl_group.setLayoutParams(lp);

			} else { // 非全屏切换全屏
				ISFULLSCREEN = true;
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 手动横屏
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
						RelativeLayout.LayoutParams.MATCH_PARENT);
				fl_group.setLayoutParams(lp);
			}

			break;

		case R.id.btn_video_back:

			if (ISFULLSCREEN) { // 全屏转半屏

				ISFULLSCREEN = false;
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 手动横屏
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
						dp2px(MainActivity.this, 200));
				fl_group.setLayoutParams(lp);

			}
			break;
		case R.id.btn_play_video:     
				if(ISPLAYING&&mMediaPlayer!=null){   //视频的播放与暂停
					mMediaPlayer.pause();
					ISPLAYING=false;
				
					btn_play_video.setBackground(getResources().getDrawable(R.drawable.icon_play));
				
				}else{
					
					btn_play_video.setBackground(getResources().getDrawable(R.drawable.icon_topause));
					mMediaPlayer.start();
					ISPLAYING=true;
			
				}
			
			break;

		default:
			break;
		}
	}
	
	
	
}
这个主页面代码。

横竖屏切换的代码如下:
case R.id.btn_full_video:

			if (ISFULLSCREEN) { // 全屏转半屏

				ISFULLSCREEN = false;
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 手动横屏
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
						dp2px(MainActivity.this, 200));
				fl_group.setLayoutParams(lp);

			} else { // 非全屏切换全屏
				ISFULLSCREEN = true;
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 手动横屏
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
						RelativeLayout.LayoutParams.MATCH_PARENT);
				fl_group.setLayoutParams(lp);
			}

			break;

最后附上xml文件:

	
    
          
        
        


不懂的欢迎大家要提问,能帮到的尽量帮。
资源下载

你可能感兴趣的:(安卓)