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

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

編輯:關於Android編程

6. 為PlayList(播放列表)寫ListView
  使用列表視圖(ListView)來顯示播放列表,在drawable文件夾下創建一個xml布局文件並叫做list_selector.xml,這個xml是用於對列表項漸變背景。
list_selector.xml <?xmlversion="1.0"encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item
 android:state_selected="false"
    android:state_pressed="false"
    android:drawable="@drawable/gradient_bg"/>
<itemandroid:state_pressed="true"
    android:drawable="@drawable/gradient_bg_hover"/>
<itemandroid:state_selected="true"
 android:state_pressed="false"
    android:drawable="@drawable/gradient_bg_hover"/>
</selector>


在drawable文件夾下創建一個xml布局文件並叫做playlist.xml,這個xml文件是為了顯示列表視圖。

playlist.xml <?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
 
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"/>
 
</LinearLayout>


再在drawable文件夾下創建一個xml布局文件並叫做playlist_item.xml,這個xml文件是為單一列表項顯示歌曲的標題。
playlist_item.xml <?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/list_selector"
    android:padding="5dp">
    <TextView
        android:id="@+id/songTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:padding="10dp"
        android:color="#f3f3f3"/>
</LinearLayout>


通過使用以上布局我們可以實現以下列表視圖通過將數據加載到它。

                                                                                                
7. 寫從SDcard讀取mp3文件的類
  到目前為止,我們已經完成了player的靜態布局,現在的實際代碼開始。創建一個新的類文件,並將其命名為SongsManager.java。這個類將從設備上的sdcard閱讀所有的文件並且過濾只留帶.mp3後綴的文件。
SongsManager.mp3 packagecom.androidhive.musicplayer;
 
importjava.io.File;
importjava.io.FilenameFilter;
importjava.util.ArrayList;
importjava.util.HashMap;
 
publicclassSongsManager {
    // SDCard Path
    finalString MEDIA_PATH = new String("/sdcard/");
    privateArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
 
    // Constructor
    publicSongsManager(){
 
    }
 
    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     * */
    publicArrayList<HashMap<String, String>> getPlayList(){
        File home = new File(MEDIA_PATH);
 
        if(home.listFiles(newFileExtensionFilter()).length > 0) {
            for(File file : home.listFiles(newFileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());
 
                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        returnsongsList;
    }
 
    /**
     * Class to filter files which are having .mp3 extension
     * */
    classFileExtensionFilterimplements FilenameFilter {
        publicbooleanaccept(File dir, String name) {
            return(name.endsWith(".mp3") || name.endsWith(".MP3"));
        }
    }
}


8. 為PlayList寫列表視圖
  為播放列表的列表視圖創建一個新的活動類,叫做PlayListActivity.java ,PlayListActivity.java 這個類通過使用SongsManager.java類來顯示歌曲列表。
PlayListActivity.java packagecom.androidhive.musicplayer;
 
importjava.util.ArrayList;
importjava.util.HashMap;
 
importandroid.app.ListActivity;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.ListAdapter;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
 
publicclassPlayListActivity extends ListActivity {
    // Songs list
    publicArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
 
    @Override
    publicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playlist);
 
        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
 
        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();
 
        // looping through playlist
        for(inti = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);
 
            // adding HashList to ArrayList
            songsListData.add(song);
        }
 
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item,newString[] { "songTitle" }, new int[] {
                        R.id.songTitle });
 
        setListAdapter(adapter);
 
        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(newOnItemClickListener() {
 
            @Override
            publicvoidonItemClick(AdapterView<?> parent, View view,
                    intposition,long id) {
                // getting listitem index
                intsongIndex = position;
 
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidBuildingMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });
    }
}

9. 輔助類的功能
創建一個新類,叫作Utilities.java,用來處理額外的工作像轉換時間進度百分比,反之亦然。此外,它具有功能將毫秒定時器轉換為時間字符串顯示在播放器的seekbar上。
Utilities.java packagecom.androidhive.musicplayer;
 
publicclassUtilities {
 
    /**
     * Function to convert milliseconds time to
     * Timer Format
     * Hours:Minutes:Seconds
     * */
    publicString milliSecondsToTimer(longmilliseconds){
        String finalTimerString = "";
        String secondsString = "";
 
        // Convert total duration into time
           inthours = (int)( milliseconds / (1000*60*60));
           intminutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
           intseconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
           // Add hours if there
           if(hours > 0){
               finalTimerString = hours + ":";
           }
 
           // Prepending 0 to seconds if it is one digit
           if(seconds < 10){
               secondsString = "0" + seconds;
           }else{
               secondsString = "" + seconds;}
 
           finalTimerString = finalTimerString + minutes + ":" + secondsString;
 
        // return timer string
        returnfinalTimerString;
    }
 
    /**
     * Function to get Progress percentage
     * @param currentDuration
     * @param totalDuration
     * */
    publicintgetProgressPercentage(longcurrentDuration,long totalDuration){
        Double percentage = (double)0;
 
        longcurrentSeconds = (int) (currentDuration / 1000);
        longtotalSeconds = (int) (totalDuration / 1000);
 
        // calculating percentage
        percentage =(((double)currentSeconds)/totalSeconds)*100;
 
        // return percentage
        returnpercentage.intValue();
    }
 
    /**
     * Function to change progress to timer
     * @param progress -
     * @param totalDuration
     * returns current duration in milliseconds
     * */
    publicintprogressToTimer(intprogress,int totalDuration) {
        intcurrentDuration = 0;
        totalDuration = (int) (totalDuration / 1000);
        currentDuration = (int) ((((double)progress) / 100) * totalDuration);
 
        // return current duration in milliseconds
        returncurrentDuration * 1000;
    }
}
作者:wangjinyu501
 

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