1. 程式人生 > >Android提高第一篇之MediaPlayer

Android提高第一篇之MediaPlayer

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

本文來自http://blog.csdn.net/hellogv/ ,引用必須註明出處! 

        前面寫了十四篇關於介面的入門文章,大家都看完和跟著練習之後,對於常用的Layout和View都會有一定的瞭解了,接下來的文章就不再強調介紹介面了,而是針對具體的常見功能而展開。

        本文介紹MediaPlayer的使用。MediaPlayer可以播放音訊和視訊,另外也可以通過VideoView來播放視訊,雖然VideoView比MediaPlayer簡單易用,但定製性不如用MediaPlayer,要視情況選擇了。MediaPlayer播放音訊比較簡單,但是要播放視訊就需要SurfaceView。SurfaceView比普通的自定義View更有繪圖上的優勢,它支援完全的OpenGL ES庫。

         先貼出本文程式執行結果的截圖,上面是播放/停止音訊,可用SeekBar來調進度,下面是播放/停止視訊,也是用SeekBar來調進度:

 

main.xml的原始碼:

[xhtml] view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout android:id="@+id/LinearLayout01"  
  3.     android:layout_width
    ="fill_parent" android:layout_height="fill_parent"  
  4.     xmlns:android="http://schemas.android.com/apk/res/android"  
  5.     android:orientation="vertical">  
  6.     <SeekBar android:id="@+id/SeekBar01" android:layout_height="wrap_content"  
  7.         android:layout_width="fill_parent"></SeekBar>  
  8.     <LinearLayout android:id="@+id/LinearLayout02"  
  9.         android:layout_width="wrap_content" android:layout_height="wrap_content">  
  10.         <Button android:id="@+id/Button01" android:layout_width="wrap_content"  
  11.             android:layout_height="wrap_content" android:text="播放音訊"></Button>  
  12.         <Button android:id="@+id/Button02" android:layout_width="wrap_content"  
  13.             android:layout_height="wrap_content" android:text="停止播放"></Button>  
  14.     </LinearLayout>  
  15.     <SeekBar android:id="@+id/SeekBar02" android:layout_height="wrap_content"  
  16.         android:layout_width="fill_parent"></SeekBar>  
  17.   
  18.     <SurfaceView android:id="@+id/SurfaceView01"  
  19.         android:layout_width="fill_parent" android:layout_height="250px"></SurfaceView>  
  20.     <LinearLayout android:id="@+id/LinearLayout02"  
  21.         android:layout_width="wrap_content" android:layout_height="wrap_content">  
  22.         <Button android:layout_width="wrap_content"  
  23.             android:layout_height="wrap_content" android:id="@+id/Button03"  
  24.             android:text="播放視訊"></Button>  
  25.         <Button android:layout_width="wrap_content"  
  26.             android:layout_height="wrap_content" android:text="停止播放" android:id="@+id/Button04"></Button>  
  27.     </LinearLayout>  
  28. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?><LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <SeekBar android:id="@+id/SeekBar01" android:layout_height="wrap_content"  android:layout_width="fill_parent"></SeekBar> <LinearLayout android:id="@+id/LinearLayout02"  android:layout_width="wrap_content" android:layout_height="wrap_content">  <Button android:id="@+id/Button01" android:layout_width="wrap_content"   android:layout_height="wrap_content" android:text="播放音訊"></Button>  <Button android:id="@+id/Button02" android:layout_width="wrap_content"   android:layout_height="wrap_content" android:text="停止播放"></Button> </LinearLayout> <SeekBar android:id="@+id/SeekBar02" android:layout_height="wrap_content"  android:layout_width="fill_parent"></SeekBar> <SurfaceView android:id="@+id/SurfaceView01"  android:layout_width="fill_parent" android:layout_height="250px"></SurfaceView> <LinearLayout android:id="@+id/LinearLayout02"  android:layout_width="wrap_content" android:layout_height="wrap_content">  <Button android:layout_width="wrap_content"   android:layout_height="wrap_content" android:id="@+id/Button03"   android:text="播放視訊"></Button>  <Button android:layout_width="wrap_content"   android:layout_height="wrap_content" android:text="停止播放" android:id="@+id/Button04"></Button> </LinearLayout></LinearLayout>

 

本文程式的原始碼,有點長:

[java] view plain copy print ?
  1. package com.testMedia;  
  2.   
  3. import java.io.IOException;    
  4. import java.util.Timer;  
  5. import java.util.TimerTask;  
  6. import android.app.Activity;    
  7. import android.media.AudioManager;  
  8. import android.media.MediaPlayer;  
  9. import android.os.Bundle;    
  10. import android.view.SurfaceHolder;  
  11. import android.view.SurfaceView;  
  12. import android.view.View;    
  13. import android.widget.Button;    
  14. import android.widget.SeekBar;  
  15. import android.widget.Toast;    
  16.   
  17.   
  18. public class testMedia extends Activity {  
  19.       /** Called when the activity is first created. */   
  20.   
  21.     private SeekBar skb_audio=null;  
  22.     private Button btn_start_audio = null;    
  23.     private Button btn_stop_audio = null;  
  24.   
  25.     private SeekBar skb_video=null;  
  26.     private Button btn_start_video = null;    
  27.     private Button btn_stop_video = null;  
  28.     private SurfaceView surfaceView;   
  29.     private SurfaceHolder surfaceHolder;   
  30.       
  31.     private MediaPlayer m = null;    
  32.     private Timer mTimer;  
  33.     private TimerTask mTimerTask;  
  34.       
  35.     private boolean isChanging=false;//互斥變數,防止定時器與SeekBar拖動時進度衝突  
  36.      @Override    
  37.     public void onCreate(Bundle savedInstanceState) {    
  38.         super.onCreate(savedInstanceState);    
  39.         setContentView(R.layout.main);    
  40.           
  41.         //----------Media控制元件設定---------//  
  42.         m=new MediaPlayer();  
  43.           
  44.         //播放結束之後彈出提示  
  45.         m.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){  
  46.             @Override  
  47.             public void onCompletion(MediaPlayer arg0) {  
  48.                 Toast.makeText(testMedia.this"結束"1000).show();  
  49.                 m.release();  
  50.             }  
  51.         });  
  52.           
  53.       //----------定時器記錄播放進度---------//  
  54.         mTimer = new Timer();  
  55.         mTimerTask = new TimerTask() {  
  56.             @Override  
  57.             public void run() {   
  58.                 if(isChanging==true)  
  59.                     return;  
  60.                   
  61.                 if(m.getVideoHeight()==0)  
  62.                     skb_audio.setProgress(m.getCurrentPosition());  
  63.                 else   
  64.                     skb_video.setProgress(m.getCurrentPosition());  
  65.             }  
  66.         };  
  67.   
  68.         mTimer.schedule(mTimerTask, 010);  
  69.           
  70.         btn_start_audio = (Button) this.findViewById(R.id.Button01);    
  71.         btn_stop_audio = (Button) this.findViewById(R.id.Button02);    
  72.         btn_start_audio.setOnClickListener(new ClickEvent());  
  73.         btn_stop_audio.setOnClickListener(new ClickEvent());  
  74.         skb_audio=(SeekBar)this.findViewById(R.id.SeekBar01);  
  75.         skb_audio.setOnSeekBarChangeListener(new SeekBarChangeEvent());  
  76.           
  77.         btn_start_video = (Button) this.findViewById(R.id.Button03);    
  78.         btn_stop_video = (Button) this.findViewById(R.id.Button04);    
  79.         btn_start_video.setOnClickListener(new ClickEvent());  
  80.         btn_stop_video.setOnClickListener(new ClickEvent());  
  81.         skb_video=(SeekBar)this.findViewById(R.id.SeekBar02);  
  82.         skb_video.setOnSeekBarChangeListener(new SeekBarChangeEvent());  
  83.         surfaceView = (SurfaceView) findViewById(R.id.SurfaceView01);  
  84.         surfaceHolder = surfaceView.getHolder();  
  85.         surfaceHolder.setFixedSize(100100);  
  86.         surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
  87.     }    
  88.        
  89.   /* 
  90.    * 按鍵事件處理 
  91.    */  
  92.   class ClickEvent implements View.OnClickListener{  
  93.     @Override  
  94.     public void onClick(View v) {  
  95.         if(v==btn_start_audio)  
  96.         {  
  97.             m.reset();//恢復到未初始化的狀態  
  98.             m=MediaPlayer.create(testMedia.this, R.raw.big);//讀取音訊  
  99.             skb_audio.setMax(m.getDuration());//設定SeekBar的長度  
  100.             try {                     
  101.                 m.prepare();    //準備  
  102.             } catch (IllegalStateException e) {           
  103.                 // TODO Auto-generated catch block                
  104.                 e.printStackTrace();                  
  105.             } catch (IOException e) {             
  106.                 // TODO Auto-generated catch block                
  107.                 e.printStackTrace();                  
  108.             }         
  109.             m.start();  //播放  
  110.         }  
  111.         else if(v==btn_stop_audio || v==btn_stop_video)  
  112.         {  
  113.             m.stop();  
  114.         }  
  115.         else if(v==btn_start_video)  
  116.         {  
  117.             m.reset();//恢復到未初始化的狀態  
  118.             m=MediaPlayer.create(testMedia.this, R.raw.test);//讀取視訊  
  119.             skb_video.setMax(m.getDuration());//設定SeekBar的長度  
  120.             m.setAudioStreamType(AudioManager.STREAM_MUSIC);  
  121.             m.setDisplay(surfaceHolder);//設定螢幕  
  122.               
  123.             try {  
  124.                 m.prepare();  
  125.                   
  126.             } catch (IllegalArgumentException e) {  
  127.                 // TODO Auto-generated catch block  
  128.                 e.printStackTrace();  
  129.             } catch (IllegalStateException e) {  
  130.                 // TODO Auto-generated catch block  
  131.                 e.printStackTrace();  
  132.             } catch (IOException e) {  
  133.                 // TODO Auto-generated catch block  
  134.                 e.printStackTrace();  
  135.             }  
  136.             m.start();  
  137.         }  
  138.     }  
  139.   }  
  140.     
  141.   /* 
  142.    * SeekBar進度改變事件 
  143.    */  
  144.   class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{  
  145.   
  146.     @Override  
  147.     public void onProgressChanged(SeekBar seekBar, int progress,  
  148.             boolean fromUser) {  
  149.         // TODO Auto-generated method stub  
  150.           
  151.     }  
  152.   
  153.     @Override  
  154.     public void onStartTrackingTouch(SeekBar seekBar) {  
  155.         isChanging=true;  
  156.     }  
  157.   
  158.     @Override  
  159.     public void onStopTrackingTouch(SeekBar seekBar) {  
  160.         m.seekTo(seekBar.getProgress());  
  161.         isChanging=false;     
  162.     }  
  163.         
  164.   }  
  165.   
  166. }  
package com.testMedia;import java.io.IOException;  import java.util.Timer;import java.util.TimerTask;import android.app.Activity;  import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;  import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.View;  import android.widget.Button;  import android.widget.SeekBar;import android.widget.Toast;  public class testMedia extends Activity {   /** Called when the activity is first created. */  private SeekBar skb_audio=null;    private Button btn_start_audio = null;      private Button btn_stop_audio = null;    private SeekBar skb_video=null;    private Button btn_start_video = null;      private Button btn_stop_video = null;    private SurfaceView surfaceView;     private SurfaceHolder surfaceHolder;         private MediaPlayer m = null;      private Timer mTimer;    private TimerTask mTimerTask;        private boolean isChanging=false;//互斥變數,防止定時器與SeekBar拖動時進度衝突     @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);                  //----------Media控制元件設定---------//        m=new MediaPlayer();                //播放結束之後彈出提示        m.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){   @Override   public void onCompletion(MediaPlayer arg0) {    Toast.makeText(testMedia.this, "結束", 1000).show();    m.release();   }        });              //----------定時器記錄播放進度---------//        mTimer = new Timer();        mTimerTask = new TimerTask() {            @Override            public void run() {              if(isChanging==true)              return;                          if(m.getVideoHeight()==0)              skb_audio.setProgress(m.getCurrentPosition());             else               skb_video.setProgress(m.getCurrentPosition());            }        };        mTimer.schedule(mTimerTask, 0, 10);          btn_start_audio = (Button) this.findViewById(R.id.Button01);          btn_stop_audio = (Button) this.findViewById(R.id.Button02);          btn_start_audio.setOnClickListener(new ClickEvent());        btn_stop_audio.setOnClickListener(new ClickEvent());        skb_audio=(SeekBar)this.findViewById(R.id.SeekBar01);        skb_audio.setOnSeekBarChangeListener(new SeekBarChangeEvent());                btn_start_video = (Button) this.findViewById(R.id.Button03);          btn_stop_video = (Button) this.findViewById(R.id.Button04);          btn_start_video.setOnClickListener(new ClickEvent());        btn_stop_video.setOnClickListener(new ClickEvent());        skb_video=(SeekBar)this.findViewById(R.id.SeekBar02);        skb_video.setOnSeekBarChangeListener(new SeekBarChangeEvent());        surfaceView = (SurfaceView) findViewById(R.id.SurfaceView01);        surfaceHolder = surfaceView.getHolder();        surfaceHolder.setFixedSize(100, 100);        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);    }         /*   * 按鍵事件處理   */  class ClickEvent implements View.OnClickListener{ @Override public void onClick(View v) {  if(v==btn_start_audio)  {   m.reset();//恢復到未初始化的狀態   m=MediaPlayer.create(testMedia.this, R.raw.big);//讀取音訊   skb_audio.setMax(m.getDuration());//設定SeekBar的長度   try {         m.prepare(); //準備   } catch (IllegalStateException e) {       // TODO Auto-generated catch block        e.printStackTrace();       } catch (IOException e) {       // TODO Auto-generated catch block        e.printStackTrace();       }     m.start(); //播放  }  else if(v==btn_stop_audio || v==btn_stop_video)  {   m.stop();  }  else if(v==btn_start_video)  {   m.reset();//恢復到未初始化的狀態   m=MediaPlayer.create(testMedia.this, R.raw.test);//讀取視訊   skb_video.setMax(m.getDuration());//設定SeekBar的長度   m.setAudioStreamType(AudioManager.STREAM_MUSIC);   m.setDisplay(surfaceHolder);//設定螢幕      try {       m.prepare();          } catch (IllegalArgumentException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IllegalStateException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }   m.start();  } }  }    /*   * SeekBar進度改變事件   */  class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{ @Override public void onProgressChanged(SeekBar seekBar, int progress,   boolean fromUser) {  // TODO Auto-generated method stub   } @Override public void onStartTrackingTouch(SeekBar seekBar) {     isChanging=true; } @Override public void onStopTrackingTouch(SeekBar seekBar) {  m.seekTo(seekBar.getProgress());     isChanging=false;  }     }}

 

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述