2010年12月4日 星期六

Android音樂播放器

音樂位置  /res/raw/

package ccc.txt;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

public class Player extends Activity {
    private ImageButton play, pause, stop;
    private MediaPlayer mp;
    private boolean bIsPaused = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //player
        mp = new MediaPlayer();
        mp = MediaPlayer.create(getBaseContext(), R.raw.test);
        //按鈕
        play = (ImageButton) findViewById(R.id.button_Play); 
        pause = (ImageButton) findViewById(R.id.button_Pause); 
        stop = (ImageButton) findViewById(R.id.button_Stop);
        //播放
        play.setOnClickListener(new ImageButton.OnClickListener() {
                public void onClick(View arg0) {
                    try {
                        mp.prepare();
                        mp.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        });
        //暫停
        pause.setOnClickListener(new ImageButton.OnClickListener() {
                 public void onClick(View arg0) {
                     if (!bIsPaused) {
                         mp.pause();
                         bIsPaused = true;
                     } else {
                         mp.start();
                         bIsPaused = false;
                     }
                 }
        });
        //停止
        stop.setOnClickListener(new ImageButton.OnClickListener() {
                public void onClick(View arg0) {
                    if (mp != null) {
                        mp.stop(); 
                    }
                }
        });
    }
    //覆蓋暫停狀態
    protected void onPause(){ 
         mp.release(); 
         super.onPause(); 
    }
}

沒有留言:

張貼留言