1. 程式人生 > >簡單實現音樂播放器

簡單實現音樂播放器

package com.example.music;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

/**	思維模式
 * 1--找佈局,找控制元件
 * 2-- 給控制元件設定點選事件兒(上一首,播放,下一首)
 * 3--實現播放方法,(上下點選事件兒都會呼叫播放方法)
 * 4--讓seekBar自動前進(),用handler,
 * 5--控制seekBar手動拖動邏輯
 * 6-- 暫停的邏輯
 * 7-- handler一直髮送訊息的邏輯;
 */
public class MainActivity extends Activity implements View.OnClickListener {

    /**
     * getExternalStorageDirectory:獲取sd卡目錄
     * getAbsolutePath:獲取絕對路徑
     */
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    //建立一個數組來存放音樂
    String[] music_array = new String[]{path + "/aa.mp3", path + "/bb.mp3", path + "/cc.mp3"};
    private SeekBar seek;
    private MediaPlayer player;
    private int index = 0;  
    //音樂在陣列中的下標;
    private boolean isPlaying = false;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //進度條重新整理間隔時間
            handler.sendEmptyMessageDelayed(1, 1000);
            int currentPosition = player.getCurrentPosition();
          //更新進度;
            seek.setProgress(currentPosition);
            if (currentPosition >= player.getDuration()) {
                //取消掉所有訊息
                handler.removeCallbacksAndMessages(null);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //尋找控制元件的內部類
        initViews();
        player = new MediaPlayer();
        //seekbar的監聽
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //獲取手放開時候的拖動進度
                int progress = seekBar.getProgress();
                player.seekTo(progress);
            }
        });
    }
    private void initViews() {
    	//獲取控制元件
        seek = (SeekBar) findViewById(R.id.progress);
        Button pre = (Button) findViewById(R.id.pre);
        Button start = (Button) findViewById(R.id.start);
        Button next = (Button) findViewById(R.id.next);
        // 註冊監聽;
        pre.setOnClickListener(this);  
        start.setOnClickListener(this);
        next.setOnClickListener(this);

    }

    /**
     * 按鈕的點選事件;
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
    	
        switch (v.getId()) {
            case R.id.pre:
                pre();
                break;
            case R.id.start:
                start();
                break;
            case R.id.next:
                next();
                break;
        }
    }
    private void start() {

        if (isPlaying) {
            player.pause();
            isPlaying = false;
            return;
        }
        try {
            player.reset(); //重置
            player.setDataSource(music_array[index]);   //設定路徑
            player.prepare();   //準備
            int duration = player.getDuration();    //得到音樂總時長;
            seek.setMax(duration);      //把總時長設定給seekBar
            player.start();     //播放
            handler.sendEmptyMessageDelayed(1,1000);
            isPlaying = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 上一首
     */
    private void pre() {
        if (index <=  0) {
            Toast.makeText(this, "已經是第一首了", Toast.LENGTH_SHORT).show();
        }else {
           index--;
           start();
        }

    }

    /**
     * 下一首
     */
    private void next() {

        if (index >= music_array.length-1) {
            Toast.makeText(this, "已經是最後一首了", Toast.LENGTH_SHORT).show();
        }else {
            index++;
            start();
        }

    }
}