android 视频播放器

这是自己以前做的一个本地视频播放器小项目,现在分享给大家:

先看几张效果图;

android 视频播放器_第1张图片


android 视频播放器_第2张图片


我这是真机截的图,所以视频画面没有截出了,真机上是可以运行的。


详细代码如下;


视频列表:

package com.multimedia.video;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.multimedia.entity.R;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 播放列表界面
 * @author Andy
 *
 */
public class VideoListActivity extends ListActivity {


	private int index=0;
	private Cursor cursor=null;
	private List<String> videoMsg=new ArrayList<String>();
	private ArrayList<Map<String,Object>> videoData= new ArrayList<Map<String,Object>>();;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		boolean able=Environment.getExternalStorageState().equals( 
                Environment.MEDIA_MOUNTED);
		if(able)
		getAllvideoMsg();
		else
		Toast.makeText(this, "sd card is unable", Toast.LENGTH_SHORT).show();
	
	}
	/**
	 * 获取本地视频信息
	 */
	private void getAllvideoMsg(){
		Uri Media_URL = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		cursor = this.getContentResolver().query(Media_URL, VideoData.listMsg, "duration>5000", null, null);
		
		int len=cursor.getCount();
		while(index<len){
			
			String info = getInfoByPosition(cursor, index);
			videoMsg.add(info);//Log.e("msg", ""+VideoData.mCursorCols[index]);
			index++;
		}
		
		for(int i =0; i < len; i++) {
		    Map<String,Object> item = new HashMap<String,Object>();
		    item.put("image", R.drawable.vp);
		    item.put("title", videoMsg.get(i));
		//    item.put("text", mListStr[i]);
		    videoData.add(item); 
		}
		SimpleAdapter adapter = new SimpleAdapter(this,videoData,R.layout.videolist,
				new String[]{"image","title"},new int[]{R.id.videoimage,R.id.videotitle});
	
		setListAdapter(adapter);
        
	}
		
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		Intent intent=new Intent(this,VideoActivity.class);
		Bundle data=new Bundle();
		data.putInt("video_index", position);
		intent.putExtra("video_bundle", data);
		startActivity(intent);
		super.onListItemClick(l, v, position, id);
	}

	private String getInfoByPosition(Cursor c,int position){
  		c.moveToPosition(position);
  		int videoTitle= c.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME);

  		int videoSize=c.getColumnIndex(MediaStore.Video.Media.SIZE);
  		int sizes=Integer.parseInt(c.getString(videoSize))/1024/1024;
  		int TotalTime=c.getColumnIndex(MediaStore.Video.Media.DURATION);
  		int time=Integer.parseInt(c.getString(TotalTime));
  		int min=time/1000/60;
  		int sec=time/1000%60;
  		
  		String info =c.getString(videoTitle)+'\n'+sizes+"MB"+"	"+min+"'"+sec;
  		return info;
  		
  	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Menu.FIRST, 0, "选择其他播放器");
		menu.add(0, Menu.FIRST+1, 0, "播放设置");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==1){
			Intent intent=new Intent(Intent.ACTION_VIEW);  
			intent.setType("video/*");  
			startActivity(Intent.createChooser(intent, getTitle())); 
		}
		else if(item.getItemId()==2){
			this.startActivity(new Intent(this,SetActivity.class));
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onDestroy() {
		if(cursor!=null){
			cursor.close();
			cursor=null;
		}
		super.onDestroy();
	}
	
}

过滤信息选择

package com.multimedia.video;

import android.provider.MediaStore;

public class VideoData {

	/**
	 * 选择性的返回列表信息
	 */
	final static String[] listMsg = new String[] {
		//	"video._id AS _id", // index must match IDCOLIDX below

			MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE,
			MediaStore.Video.Media.DURATION
	};
	
	final static String[] showMsg = new String[] {
		//	"video._id AS _id", // index must match IDCOLIDX below
		MediaStore.Video.Media.DATA,
		MediaStore.Video.Media.DISPLAY_NAME
			
	};
	
	 static int index=0;
	 
}

视频播放界面

package com.multimedia.video;

import com.multimedia.entity.R;
import com.multimedia.entity.R.id;
import com.multimedia.entity.R.layout;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;

public class VideoActivity extends Activity {

	
	@Override
	protected void onNewIntent(Intent intent) {Log.e("msg", "newintent");
		/*Uri uri=intent.getData();
		cursor = this.getContentResolver().query(uri, VideoData.showMsg, "duration>2000", null, null);
		super.onNewIntent(intent);*/
	}

	private SurfaceView sfv;
	private SeekBar seekbar;
	private Button btstart,btstop,btnext,btprev,btpause,btresume;//
	private VideoPlayer myvideo;
	//控件是否可见
	 boolean cansee=true;
	 Cursor cursor=null;
	 int current_index=0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);*/
		setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.videoplayer);

		getview();
		
		Bundle b=getIntent().getBundleExtra("video_bundle");
		if(b!=null){
		Uri Media_URL = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		cursor = this.getContentResolver().query(Media_URL, VideoData.showMsg, "duration>5000", null, null);
		current_index=b.getInt("video_index");
		}else{
			String addres=getIntent().getData().toString();
			Uri uri=Uri.parse(addres.substring(addres.indexOf("/sdcard"), addres.length()));Log.e("msg", "uri="+uri);
			cursor = this.getContentResolver().query(uri, VideoData.showMsg, "duration>2000", null, null);
		}

	}
	/**
	 * 获取控件对象
	 */
	private void getview(){
		
		ClickMonitor cliM=new ClickMonitor();
		sfv=(SurfaceView)findViewById(R.id.surfaceView1);
		seekbar=(SeekBar)findViewById(R.id.seekbar);
		
		btprev=(Button)findViewById(R.id.btnPrev);
		btprev.setOnClickListener(cliM);
		btstart=(Button)findViewById(R.id.btnPlay);
		btstart.setOnClickListener(cliM);
		btstart.setVisibility(View.GONE);
		btpause=(Button)findViewById(R.id.btnPause);
	//	btpause.setVisibility(View.GONE);
		btpause.setOnClickListener(cliM);
		btresume=(Button)findViewById(R.id.btnResume);
		btresume.setVisibility(View.GONE);
		btresume.setOnClickListener(cliM);
		btstop=(Button)findViewById(R.id.btnStop);
		btstop.setOnClickListener(cliM);
		btnext=(Button)findViewById(R.id.btnNext);
		btnext.setOnClickListener(cliM);
		
		myvideo=new VideoPlayer(getApplicationContext(), sfv,seekbar,this);
		seekbar.setOnSeekBarChangeListener(new SeekBarMonitor());
	}
	/**
	 * 设置控件可见度
	 * @param view
	 */
	void setVisibleWidget(int view){
		if(view==View.GONE){
			seekbar.setVisibility(view);
			btnext.setVisibility(view);
			btprev.setVisibility(view);
			btpause.setVisibility(view);
			btresume.setVisibility(view);
			btstart.setVisibility(view);
			btstop.setVisibility(view);
		}
		else{
			if(myvideo.isPlaying()){
				seekbar.setVisibility(view);
				btnext.setVisibility(view);
				btpause.setVisibility(view);//pause enable
				btprev.setVisibility(view);
				btstop.setVisibility(view);
			}else if(true==myvideo.hasstop){
				seekbar.setVisibility(view);
				btnext.setVisibility(view);
				btprev.setVisibility(view);
				btstart.setVisibility(view);//start enable
				btstop.setVisibility(view);
			}else if(false==myvideo.hasstop){
				seekbar.setVisibility(view);
				btnext.setVisibility(view);
				btprev.setVisibility(view);
				btresume.setVisibility(view);//resume enable
				btstop.setVisibility(view);
			}
		}
	}
	
	@Override
	protected void onStart() {Log.e("msg", "onstart");
		
		super.onStart();
	}

	@Override
	protected void onPause() {
		
		super.onPause();
	}

	@Override
	protected void onResume() {
		
		super.onResume();
	}

	@Override
	protected void onStop() {
		
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		myvideo.destroy();
		super.onDestroy();
	}

	void contrlVisible(){
		if(cansee)
			setVisibleWidget(View.VISIBLE);
		else
			setVisibleWidget(View.GONE);
			
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		int action =event.getAction();
		
		switch(action){
		case MotionEvent.ACTION_DOWN:
			cansee=!cansee;
			contrlVisible();
		break;
		
		case MotionEvent.ACTION_MOVE:				
			
		break;
			
		case MotionEvent.ACTION_UP:					
			
		break;
		}
		return super.onTouchEvent(event);
	}

	class ClickMonitor implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			if(v==btstart){
				myvideo.startPlay();
				btstart.setVisibility(View.GONE);
				btpause.setVisibility(View.VISIBLE);
				btresume.setVisibility(View.GONE);
				
			}
			else if(v==btpause){
				myvideo.pause();
				btstart.setVisibility(View.GONE);
				btpause.setVisibility(View.GONE);
				btresume.setVisibility(View.VISIBLE);
			}
			else if(v==btstop){
				myvideo.stop();
				btstart.setVisibility(View.VISIBLE);
				btpause.setVisibility(View.GONE);
				btresume.setVisibility(View.GONE);
			}
			else if(v==btresume){
				myvideo.resume();
				btstart.setVisibility(View.GONE);
				btpause.setVisibility(View.VISIBLE);
				btresume.setVisibility(View.GONE);
			}
			else if(v==btnext){
				myvideo.next();
				btstart.setVisibility(View.GONE);
				btpause.setVisibility(View.VISIBLE);
				btresume.setVisibility(View.GONE);
			}
			else if(v==btprev){
				myvideo.previous();
				btstart.setVisibility(View.GONE);
				btpause.setVisibility(View.VISIBLE);
				btresume.setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	//	int type = this.getResources().getConfiguration().orientation;  
		     
		   if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {  
		        //切换到了横屏   
		   } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {  
		       //切换到了竖屏   
		   }  

		super.onConfigurationChanged(newConfig);
	}

	class SeekBarMonitor implements SeekBar.OnSeekBarChangeListener{

		int currentpos;
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			
			currentpos=progress * myvideo.myplayer.getDuration() / seekBar.getMax();

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			
			
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			myvideo.myplayer.seekTo(currentpos);
		}
		
	}

}


控制播放;

package com.multimedia.video;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.VideoView;

public class VideoPlayer implements OnBufferingUpdateListener,
		OnCompletionListener, MediaPlayer.OnPreparedListener,
		Callback,OnErrorListener{

	public static final int UPDATE=1;
	public static final int VISIBLE=2;
	private int video_w,video_h;
	private SurfaceHolder sfh;
	private SurfaceView sfv;
	protected MediaPlayer myplayer;
	private SeekBar seekbar;
	private Timer timer=new Timer();
	private MyTask task;
	private boolean desroyed=false;//canvas desroy
	private Context mcontext;
	private VideoActivity vida;
	//控制可见性,
	public boolean hasstop=false,pausing=false;
	private int count=0;
	private int current_pos,total_time ;

	public VideoPlayer(Context mcontext,SurfaceView sfv,SeekBar seekbar,VideoActivity vida){
		
		this.mcontext=mcontext;
		this.vida=vida;
		this.sfv=sfv;
		this.seekbar=seekbar;
		this.sfv.setFocusable(true);
		sfh=this.sfv.getHolder();
		sfh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		sfh.setKeepScreenOn(true);
		sfh.addCallback(this);
		task=new MyTask();
		timer.schedule(task, 0, 1000);
		myplayer = new MediaPlayer();
		
	}
	
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case VISIBLE:
				vida.cansee=false;
				vida.contrlVisible();
				break;

			case UPDATE:
				current_pos = myplayer.getCurrentPosition();
				total_time = myplayer.getDuration();
				if (total_time > 0) {
					int pos = seekbar.getMax() * current_pos / total_time;
					seekbar.setProgress(pos);
				}
				break;
			}
			
		};
	};
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
	
			playStart();

		
		Log.e("msg", "surfaceCreated");
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
		Log.e("msg", "surfaceChanged");
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		
		desroyed=true;
		if(myplayer!=null&&myplayer.isPlaying()){
			myplayer.stop();
		}
		Log.e("msg", "surfaceDestroyed");
	}
	
	private void playStart(){
		
		String path=getDateByPosition(vida.cursor, vida.current_index);
		Toast.makeText(mcontext, getInfoByPosition(vida.cursor, vida.current_index), Toast.LENGTH_SHORT).show();
			try {
				hasstop=false;
				seekbar.setEnabled(true);
				myplayer.reset();
				myplayer.setDataSource(path);
				myplayer.setScreenOnWhilePlaying(true);
				myplayer.setDisplay(sfh);
				myplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				myplayer.setWakeMode(mcontext, PowerManager.PARTIAL_WAKE_LOCK);
				myplayer.setOnPreparedListener(this);
				myplayer.setOnCompletionListener(this);
				myplayer.setOnBufferingUpdateListener(this);
				myplayer.setOnErrorListener(this);
				
				myplayer.prepare();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
	}
	
	public void startPlay(){
		playStart();
		myplayer.start();
		
	}
	public void resume(){
		if(!myplayer.isPlaying()){
			pausing=false;
			myplayer.start();
			if(desroyed){
				desroyed=false;
				myplayer.seekTo(current_pos);
			}
		}
	}
	
	public void pause(){
		if(myplayer.isPlaying()){
			pausing=true;
			myplayer.pause();
		}
	}
	
	public void stop(){
		current_pos=0;total_time=0;
		if (myplayer != null) { 
			pausing=true;
			hasstop=true;
			myplayer.stop();
			seekbar.setProgress(0);
			seekbar.setEnabled(false);
        } 
	}
	
	public void setLooop(boolean loop){
		myplayer.setLooping(loop);
	}
	
	public boolean isPlaying(){
		return myplayer.isPlaying();
	}
	
	public void previous() {
	  		if (vida.current_index == 0) {
	  			vida.current_index = vida.cursor.getCount() - 1;
	  		} else {
	  			vida.current_index--;
	  		}
	  		current_pos=0;total_time=0;
	  		pausing=false;
	  		playStart();
	  	}
	
	public void next() {
	  		if (vida.current_index == vida.cursor.getCount() - 1) {
	  			vida.current_index = 0;
	  		} else {
	  			vida.current_index++;
	  		}
	  		current_pos=0;total_time=0;
	  		pausing=false;
	  		playStart();
	  	}
	  	 
	private String getDateByPosition(Cursor c,int position){
  		c.moveToPosition(position);
  		int dataColumn = c.getColumnIndex(MediaStore.Video.Media.DATA);		
  		String data = c.getString(dataColumn);
  		return data;
  	}
	
	private String getInfoByPosition(Cursor c,int position){
  		c.moveToPosition(position);
  		int videoTitle= c.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME);

  		String info =c.getString(videoTitle);
  		return info;
  		
  	}
	
	public void destroy(){
		if(myplayer!=null){
			myplayer.stop();
			myplayer.release(); 
			myplayer = null; 
		}
		if(vida.cursor!=null){
			vida.cursor.close();
			vida.cursor=null;
		}
		if(timer!=null){
			timer.cancel();
			task.cancel();
			timer=null;
			task=null;
		}
	}
	
	public void controlVolume(){
		AudioManager amg=(AudioManager)this.mcontext.getSystemService(Context.AUDIO_SERVICE);
		float current_volume=amg.getStreamVolume(AudioManager.STREAM_MUSIC);
		float max_volume=amg.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volume=current_volume/max_volume;
		
		myplayer.setVolume(volume, volume);
	}
	
	
	private class MyTask extends TimerTask{

		@Override
		public void run() {
			if(myplayer==null)
				return;
			if(myplayer.isPlaying()&&seekbar.isPressed()==false){
				Message msg=Message.obtain();
				msg.what=UPDATE;
				handler.sendMessage(msg);
			}
			if(vida.cansee){
				count++;
				if(count%5==0){
					count=0;
					Message msg=Message.obtain();
					msg.what=VISIBLE;
					handler.sendMessage(msg);
				}
			}
		}
	}
	
	@Override
	public void onPrepared(MediaPlayer mp) {
		video_w=myplayer.getVideoWidth();
		video_h=myplayer.getVideoHeight();
		
		if(video_w!=0&&video_h!=0){
			if(!pausing){
				sfh.setFixedSize(video_w,video_h);
				myplayer.start();
			if(current_pos>0)
				myplayer.seekTo(current_pos);
			}
		}

		Log.e("msg", "prepare");
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		if(myplayer.isLooping())
			playStart();
		else
			next();
		Log.e("msg", "complete");
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		seekbar.setSecondaryProgress(percent);
		Log.e("msg", "buffer");
	}

	@Override
	public boolean onError(MediaPlayer mp, int arg1, int arg2) {
		destroy();
		return false;
	}


}


目前这个播放器功能只有播放,暂停,下一首,上一首等基本功能,可能还会有bug,没办法时间仓促,以后继续完善。今天先到这里。


你可能感兴趣的:(android,视频播放器,多媒体)