Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android構建音頻播放器教程(三)

Android構建音頻播放器教程(三)

編輯:關於Android編程

10. 為Audio Player寫相關類文件
  打開你的主要活動類(MainActivity)處理主要player界面,並且繼承 OnCompletionListener, SeekBar.OnSeekBarChangeListener.在這種情況下,我的主要活動名稱是AndroidBuildingMusicPlayerActivity。
AndroidBuildingMusicPlayerActivity.java publicclassAndroidBuildingMusicPlayerActivityextendsActivity
       implementsOnCompletionListener, SeekBar.OnSeekBarChangeListener {

現在聲明所有變量需要為此音頻播放器類。(audio player class)

 

AndroidBuildingMusicPlayerActivity.java
publicclassAndroidBuildingMusicPlayerActivityextendsActivity
       implementsOnCompletionListener, SeekBar.OnSeekBarChangeListener {
    privateImageButton btnPlay;
    privateImageButton btnForward;
    privateImageButton btnBackward;
    privateImageButton btnNext;
    privateImageButton btnPrevious;
    privateImageButton btnPlaylist;
    privateImageButton btnRepeat;
    privateImageButton btnShuffle;
    privateSeekBar songProgressBar;
    privateTextView songTitleLabel;
    privateTextView songCurrentDurationLabel;
    privateTextView songTotalDurationLabel;
    // Media Player
    private MediaPlayer mp;
    // Handler to update UI timer, progress bar etc,.
    privateHandler mHandler =newHandler();;
    privateSongsManager songManager;
    privateUtilities utils;
    privateintseekForwardTime =5000;// 5000 milliseconds
    privateintseekBackwardTime =5000;// 5000 milliseconds
    privateintcurrentSongIndex =0;
    privatebooleanisShuffle =false;
    privatebooleanisRepeat =false;
    privateArrayList<HashMap<String, String>> songsList =newArrayList<HashMap<String, String>>();

 


現在引用XML布局的所有按鈕,圖像類

AndroidBuildingMusicPlayerActivity.java
// All player buttons
        btnPlay = (ImageButton) findViewById(R.id.btnPlay);
        btnForward = (ImageButton) findViewById(R.id.btnForward);
        btnBackward = (ImageButton) findViewById(R.id.btnBackward);
        btnNext = (ImageButton) findViewById(R.id.btnNext);
        btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
        btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
        btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
        btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
        songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
        songTitleLabel = (TextView) findViewById(R.id.songTitle);
        songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
        songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
        // Mediaplayer
        mp =newMediaPlayer();
        songManager =newSongsManager();
        utils =newUtilities();
        // Listeners
        songProgressBar.setOnSeekBarChangeListener(this);// Important
        mp.setOnCompletionListener(this);// Important
        // Getting all songs list
        songsList = songManager.getPlayList();


1.加載播放列表(PlayList)
  為playlist button寫單擊事件偵聽器,在點擊播放按鈕時我們需要加載PlayListAcitivity.java ,從列表中選擇一個特定的歌曲上我們需要得到songIndex。
  AndroidBuildingMusicPlayerActivity.java /**
         * Button Click event for Play list click event
         * Launches list activity which displays list of songs
         * */
        btnPlaylist.setOnClickListener(newView.OnClickListener() {
            @Override
            publicvoidonClick(View arg0) {
                Intent i =newIntent(getApplicationContext(), PlayListActivity.class);
                startActivityForResult(i,100);
            }
        });

 

接收選定的歌曲索引增加以下功能(請確保您添加此功能以外的onCreate方法)

AndroidBuildingMusicPlayerActivity.java /**
     * Receiving song index from playlist view
     * and play the song
     * */
    @Override
    protectedvoidonActivityResult(intrequestCode,
                                     intresultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
             currentSongIndex = data.getExtras().getInt("songIndex");
             // play selected song
             playSong(currentSongIndex);
        }
    }


2.Playing Song(播放歌曲)
  添加以下功能添加到你的類,這個函數接受songIndex作為參數並播放。當開始播放一首歌切換播放按鈕暫停按鈕狀態。
AndroidBuildingMusicPlayerActivity.java /**
     * Function to play a song
     * @param songIndex - index of song
     * */
    publicvoid playSong(intsongIndex){
        // Play song
        try{
            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);
            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);
            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);
            // Updating progress bar
            updateProgressBar();
        }catch(IllegalArgumentException e) {
            e.printStackTrace();
        }catch(IllegalStateException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

 

3.Forward / Backward button click events(向前向後事件監聽)
  添加按鈕事件偵聽器,歌指定秒前和向後
  1.前進按鈕單擊事件-移動歌曲以指定數量的秒向前,

AndroidBuildingMusicPlayerActivity.java /**
         * Forward button click event
         * Forwards song specified seconds
         * */
        btnForward.setOnClickListener(newView.OnClickListener() {
            @Override
            publicvoidonClick(View arg0) {
                // get current song position
                intcurrentPosition = mp.getCurrentPosition();
                // check if seekForward time is lesser than song duration
                if(currentPosition + seekForwardTime <= mp.getDuration()){
                    // forward song
                    mp.seekTo(currentPosition + seekForwardTime);
                }else{
                    // forward to end position
                    mp.seekTo(mp.getDuration());
                }
            }
        });


  2.向後按鈕單擊事件-移動歌曲以指定秒數落後,

AndroidBuildingMusicPlayerActivity.java /**
         * Backward button click event
         * Backward song to specified seconds
         * */
        btnBackward.setOnClickListener(newView.OnClickListener() {
            @Override
            publicvoidonClick(View arg0) {
                // get current song position
                intcurrentPosition = mp.getCurrentPosition();
                // check if seekBackward time is greater than 0 sec
                if(currentPosition - seekBackwardTime >= 0){
                    // forward song
                    mp.seekTo(currentPosition - seekBackwardTime);
                }else{
                    // backward to starting position
                    mp.seekTo(0);
                }
            }
        });

 

4.Next / Back button click events(上一首下一首事件監聽)
  點擊添加按鈕偵聽器的下一個和上一個。

  1.Next按鈕單擊事件-從播放列表播放下一首歌曲(不是最後一首)
AndroidBuildingMusicPlayerActivity.java /**
         * Next button click event
         * Plays next song by taking currentSongIndex + 1
         * */
        btnNext.setOnClickListener(newView.OnClickListener() {
            @Override
            publicvoidonClick(View arg0) {
                // check if next song is there or not
                if(currentSongIndex < (songsList.size() - 1)){
                    playSong(currentSongIndex +1);
                    currentSongIndex = currentSongIndex +1;
                }else{
                    // play first song
                    playSong(0);
                    currentSongIndex =0;
                }
            }
        });

 
  2.後退按鈕單擊事件——播放前一首歌曲(不是第一首)
  AndroidBuildingMusicPlayerActivity.java /**         * Back button click event         * Plays previous song by currentSongIndex - 1         * */        btnPrevious.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View arg0) {                if(currentSongIndex > 0){                    playSong(currentSongIndex - 1);                    currentSongIndex = currentSongIndex - 1;                }else{                    // play last song                    playSong(songsList.size() - 1);                    currentSongIndex = songsList.size() - 1;                }            }        });
5.更新SeekBar的進度和時間
  要更新進度條計時器,我實現了在後台運行一個後台線程,使用一個Handler

AndroidBuildingMusicPlayerActivity.java /**     * Update timer on seekbar     * */    publicvoidupdateProgressBar() {        mHandler.postDelayed(mUpdateTimeTask,100);    }      /**     * Background Runnable thread     * */    privateRunnable mUpdateTimeTask = new Runnable() {           publicvoidrun() {               longtotalDuration = mp.getDuration();               longcurrentDuration = mp.getCurrentPosition();               // Displaying Total Duration time               songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));               // Displaying time completed playing               songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));               // Updating progress bar               intprogress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));               //Log.d("Progress", ""+progress);               songProgressBar.setProgress(progress);               // Running this thread after 100 milliseconds               mHandler.postDelayed(this,100);           }        };    /**     *     * */    @Override    publicvoidonProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {    }    /**     * When user starts moving the progress handler     * */    @Override    publicvoidonStartTrackingTouch(SeekBar seekBar) {        // remove message Handler from updating progress bar        mHandler.removeCallbacks(mUpdateTimeTask);    }    /**     * When user stops moving the progress hanlder     * */    @Override    publicvoidonStopTrackingTouch(SeekBar seekBar) {        mHandler.removeCallbacks(mUpdateTimeTask);        inttotalDuration = mp.getDuration();        intcurrentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);        // forward or backward to certain seconds        mp.seekTo(currentPosition);        // update timer progress again        updateProgressBar();    }

 


6.Repeat button click event(事件監聽)
  在單擊按鈕重復isRepeat我們需要設置為true,反之亦然。我們也需要改變圖像源重復按鈕來集中狀態


AndroidBuildingMusicPlayerActivity.java /**         * Button Click event for Repeat button         * Enables repeat flag to true         * */        btnRepeat.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View arg0) {                if(isRepeat){                    isRepeat = false;                    Toast.makeText(getApplicationContext(),"Repeat is OFF", Toast.LENGTH_SHORT).show();                    btnRepeat.setImageResource(R.drawable.btn_repeat);                }else{                    // make repeat to true                    isRepeat = true;                    Toast.makeText(getApplicationContext(),"Repeat is ON", Toast.LENGTH_SHORT).show();                    // make shuffle to false                    isShuffle = false;                    btnRepeat.setImageResource(R.drawable.btn_repeat_focused);                    btnShuffle.setImageResource(R.drawable.btn_shuffle);                }            }        });

 


7.Shuffle button click event(事件監聽)
“洗牌”按鈕上,我們需要設置isShuffle為true,反之亦然。此外,我們需要改變圖像源洗牌按鈕集中狀態。


AndroidBuildingMusicPlayerActivity.java /**         * Button Click event for Shuffle button         * Enables shuffle flag to true         * */        btnShuffle.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View arg0) {                if(isShuffle){                    isShuffle = false;                    Toast.makeText(getApplicationContext(),"Shuffle is OFF", Toast.LENGTH_SHORT).show();                    btnShuffle.setImageResource(R.drawable.btn_shuffle);                }else{                    // make repeat to true                    isShuffle=true;                    Toast.makeText(getApplicationContext(),"Shuffle is ON", Toast.LENGTH_SHORT).show();                    // make shuffle to false                    isRepeat = false;                    btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);                    btnRepeat.setImageResource(R.drawable.btn_repeat);                }            }        });

 

8.繼承 song onCompletion Listener接口
   實現這個監聽器很重要,當歌曲播放完畢後他會通知你,在這個方法中,我們需要自動播放下一首歌曲根據重復和shuffle條件。www.2cto.com
 
AndroidBuildingMusicPlayerActivity.java
/**     * On Song Playing completed     * if repeat is ON play same song again     * if shuffle is ON play random song     * */    @Override    publicvoidonCompletion(MediaPlayer arg0) {        // check for repeat is ON or OFF        if(isRepeat){            // repeat is on play same song again            playSong(currentSongIndex);        }elseif(isShuffle){            // shuffle is on - play a random song            Random rand = new Random();            currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;            playSong(currentSongIndex);        }else{            // no repeat or shuffle ON - play next song            if(currentSongIndex < (songsList.size() - 1)){                playSong(currentSongIndex + 1);                currentSongIndex = currentSongIndex + 1;            }else{                // play first song                playSong(0);                currentSongIndex = 0;            }        } 

作者:wangjinyu501

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved