一.MediaPlayer Android的MediaPlayer包含了Audio和video的播放功能,在Android的界面上,Music和Video兩個應用程式都是調用MediaPlayer實現的MediaPlayer在底層是基於OpenCore(PacketVideo)的庫實現的 二.創建M ...
一.MediaPlayer
Android的MediaPlayer包含了Audio和video的播放功能,在Android的界面上,Music和Video兩個應用程式都是調用MediaPlayer實現的
MediaPlayer在底層是基於OpenCore(PacketVideo)的庫實現的
二.創建MediaPlayer實例
1:MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/sdcard/test.mp3");
2:MediaPlayer mp = MediaPlayer.create(this, R.raw.test);
三.MediaPlayer API
Android通過控制播放器的狀態的方式來控制媒體文件的播放
prepare()和prepareAsync() 提供了同步和非同步兩種方式設置播放器進入prepare狀態,需要註意的是,如果MediaPlayer實例是由create方法創建的,那麼第一次啟動播放前不需要再調用prepare()了,因為create方法里已經調用過了。
start()是真正啟動文件播放的方法,pause()和stop()比較簡單,起到暫停和停止播放的作用,
seekTo()是定位方法,可以讓播放器從指定的位置開始播放,需要註意的是該方法是個非同步方法,也就是說該方法返回時並不意味著定位完成,尤其是播放的網路文件,真正定位完成時會觸發OnSeekComplete.onSeekComplete(),如果需要是可以調用setOnSeekCompleteListener(OnSeekCompleteListener)設置監聽器來處理的。
release()可以釋放播放器占用的資源,一旦確定不再使用播放器時應當儘早調用它釋放資源。
reset()可以使播放器從Error狀態中恢復過來,重新會到Idle狀態。
四.例子,代碼
4.1播放音樂
public class PlayMusicActivity extends Activity { private SeekBar sb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_music); sb=(SeekBar)findViewById(R.id.sb); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { if(mp!=null) mp.seekTo(seekBar.getProgress()); } }); } //播放音樂 MediaPlayer mp; boolean isRun=true; public void doPlay(View view){ if(mp!=null) return; isRun=true; mp=new MediaPlayer();//構建一個播放器對象 mp.reset();//點擊播放重置 String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/nobody.mp3";//歌曲的路徑 try { mp.setDataSource(path);//設置要播放的文件路徑 mp.setAudioStreamType(AudioManager.STREAM_MUSIC);//設置多媒體類型 mp.prepare();//準備就緒 sb.setMax(mp.getDuration());//設置進度條最大值為音頻文件的持續時間 mp.start();//開始播放 //更新進度 new Thread(new Runnable() { @Override public void run() { while(isRun&&mp.getCurrentPosition()<=sb.getMax()){ sb.setProgress(mp.getCurrentPosition()); SystemClock.sleep(200); } } }).start(); } catch (IOException e) { e.printStackTrace(); } } public void doPause(View view){ if(mp==null) return; if(mp.isPlaying()){ mp.pause(); ((Button)view).setText("繼續播放"); }else{ mp.start(); ((Button)view).setText("暫停"); } } public void doStop(View view){ if(mp!=null&&mp.isPlaying()){ isRun=false; mp.stop(); mp.release(); mp=null; } } @Override protected void onDestroy() { super.onDestroy(); doStop(null); } }
4.2播放視頻
1.方法一:
//播放視頻一 public void playVedio_1(View view){ Intent intent=new Intent(Intent.ACTION_VIEW); Uri uri= Uri.parse("file:///sdcard/goodmm.mp4");//更換為你自己的路徑 intent.setDataAndType(uri,"video/mp4"); startActivity(intent); }
2.方法二:
//播放視頻二 public void playVedio_2(View view){ Intent intent=new Intent(this,PlayVideoActivity.class); startActivity(intent); }
public class PlayVideoActivity extends Activity { private VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_video); videoView=(VideoView)findViewById(R.id.videoView); videoView.setMediaController(new MediaController(this)); Uri uri= Uri.parse("file:///sdcard/goodmm.mp4"); videoView.setVideoURI(uri); new Thread(new Runnable() { @Override public void run() { SystemClock.sleep(5000); runOnUiThread(new Runnable() { @Override public void run() { videoView.setBackground(null); videoView.start(); } }); } }).start(); } }
3.方法三:
//播放視頻三 public void playVedio_3(View view){ Intent intent=new Intent(this,PlayVideo_2Activity.class); startActivity(intent); }
public class PlayVideo_2Activity extends Activity { private MediaPlayer mp; private SurfaceView sfView; private SurfaceHolder holder; private SeekBar sb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_video_2); sb=(SeekBar)findViewById(R.id.sb); sfView=(SurfaceView)findViewById(R.id.sfView); holder=sfView.getHolder(); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { if(mp!=null) mp.seekTo(seekBar.getProgress()); } }); } boolean isRun=true; public void doPlay(View view){ if(mp!=null) return; isRun=true; mp=new MediaPlayer(); mp.reset(); String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/goodmm.mp4"; try { mp.setDataSource(path);//設置數據源 mp.setAudioStreamType(AudioManager.STREAM_MUSIC); mp.setDisplay(holder);//設置顯示位置 mp.prepare(); sb.setMax(mp.getDuration()); sfView.setBackground(null); mp.start(); new Thread(new Runnable() { @Override public void run() { while (isRun&&mp.getCurrentPosition()<=sb.getMax()){ sb.setProgress(mp.getCurrentPosition()); SystemClock.sleep(200); } } }).start(); } catch (IOException e) { e.printStackTrace(); } } public void doPause(View view){ if(mp==null) return; if(mp.isPlaying()){ mp.pause(); ((Button)view).setText("繼續播放"); }else{ mp.start(); ((Button)view).setText("暫停"); } } public void doStop(View view){ if(mp!=null&&mp.isPlaying()){ isRun=false; mp.stop(); mp.release(); mp=null; } } @Override protected void onDestroy() { super.onDestroy(); doStop(null); } }
4.3錄製
MediaRecorder:
Android的MediaRecorder包含了Audio和video的記錄功能,在Android的界面上,Music和Video兩個應用程式都是調用MediaRecorder實現的。
MediaRecorder在底層是基於OpenCore(PacketVideo)的庫實現的。
4.3.1錄製音頻並播放
//錄製音頻
public void recorder_test(View view){ Intent intent=new Intent(this,RecorderActivity.class); startActivity(intent); }
public class RecorderActivity extends Activity { private MediaRecorder recorder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recorder); } //開始錄音 public void doStart(View view){ if(recorder!=null) return; recorder=new MediaRecorder();//構建了一個錄音設備 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//設置聲音來源 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//設置錄音文件格式 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//設置聲音編碼類型 String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luyin.3gp"; recorder.setOutputFile(path);//設置輸出文件位置 try { recorder.prepare();//錄音設備就緒 recorder.start();//開始錄音 } catch (IOException e) { e.printStackTrace(); } } //錄音結束 public void doStop(View view){ if(recorder!=null){ recorder.stop(); recorder.release(); recorder=null; } } //播放錄音 MediaPlayer mp; public void doPlay(View view){ if(mp!=null) return; mp=new MediaPlayer(); mp.reset(); String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luyin.3gp"; try { mp.setDataSource(path); mp.prepare(); mp.start(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); doStop(null); } }
4.3.2錄製視頻並播放
//錄製視頻 public void recorder_video_test(View view){ Intent intent=new Intent(this,Recorder_VideoActivity.class); startActivity(intent); }
public class Recorder_VideoActivity extends Activity { private MediaPlayer mp; private SurfaceView sfView; private SurfaceHolder holder; private MediaRecorder recorder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recorder__video); sfView=(SurfaceView)findViewById(R.id.sfView); holder=sfView.getHolder(); } //開始錄像 public void doStart(View view){ recorder=new MediaRecorder(); recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luxiang.mp4"; recorder.setOutputFile(path); recorder.setPreviewDisplay(holder.getSurface()); try { recorder.prepare(); recorder.start(); } catch (IOException e) { e.printStackTrace(); } } public void doStop(View view){ if(recorder!=null){ try{ recorder.stop(); }catch (Exception ex){ ex.printStackTrace(); } } } public void doPlay(View view){ if(mp!=null) return; mp=new MediaPlayer(); mp.reset(); String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luxiang.mp4"; try { mp.setDataSource(path);//設置數據源 mp.setAudioStreamType(AudioManager.STREAM_MUSIC); mp.setDisplay(holder);//設置顯示位置 mp.prepare(); sfView.setBackground(null); mp.start(); }catch (Exception ex){ ex.printStackTrace(); } } }