21天學習android開發教程之MediaPlayer_Android

來源:互聯網
上載者:User

本文介紹MediaPlayer的使用。MediaPlayer可以播放音頻和視頻,另外也可以通過VideoView來播放視頻,雖然VideoView比MediaPlayer簡單易用,但定製性不如用MediaPlayer,要視情況選擇了。MediaPlayer播放音頻比較簡單,但是要播放視頻就需要SurfaceView。SurfaceView比普通的自訂View更有繪圖上的優勢,它支援完全的OpenGL ES庫。
先貼出本文程式運行結果的截圖,上面是播放/停止音頻,可用SeekBar來調進度,下面是播放/停止視頻,也是用SeekBar來調進度:

main.xml的源碼:

<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">  <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 android:id="@+id/Button02" android:layout_width="wrap_content"       android:layout_height="wrap_content" android:text="停止播放">    <seekbar android:id="@+id/SeekBar02" android:layout_height="wrap_content"     android:layout_width="fill_parent">  <surfaceview android:id="@+id/SurfaceView01"     android:layout_width="fill_parent" android:layout_height="250px">  <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 android:layout_width="wrap_content"       android:layout_height="wrap_content" android:text="停止播放" android:id="@+id/Button04">

本文程式的源碼,有點長:

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;    }    }}

以上就是21天學習android開發教程第一篇關於MediaPlayer的相關介紹,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.