1. 程式人生 > >android音樂播放器開發 SweetMusicPlayer 載入歌曲列表

android音樂播放器開發 SweetMusicPlayer 載入歌曲列表

路徑 本地 exc tao near import 設置 優先 特殊

上一篇寫了播放器的總體實現思路,http://blog.csdn.net/huweigoodboy/article/details/39855653,如今來總結下載入歌曲列表。


代碼地址:https://github.com/huweigoodboy/SweetMusicPlayer


比較好的實現思路就是。自己維護一個SQLite數據庫,然後音樂信息都從sd卡上掃描,優點有非常多,可是這樣做的話代碼量會比較大,寫了一段掃描sd卡的代碼。然後發現掃描音樂的速度簡直慢的驚人,可能自己的文件夾太多,太深。眼下還沒想到一個比較好的算法去高速掃描sd卡。
樓主比較偷懶,android自己本身有一個關於媒體信息的數據庫。直接用這個就夠了,你可能又要吐槽了,假設我要制作一個能在線播放音樂的播放器,下載歌曲後。這個自帶的數據庫不刷新歌曲怎麽辦。哈哈。我這是個本地播放器。我就不考慮這些事了。

不,作為一個程序猿。這樣的態度可不好。

我眼下能想到的是。每次下完一首歌讓android系統自己去掃描一下。


ok,還是進入正題吧。

一,從數據庫載入歌曲信息

已經存在這個數據庫,我們就直接從裏面獲取唄,android系統通過ContextProvider把這個暴露出來。我們僅僅須要獲得一個ContextResolver對象去獲得歌曲信息。

基本的方法
Cursor android.content.ContentResolver.query(Uri uri, String[] projection,String selection,

String[] selectionArgs,String sortOrder)
上面參數的主要意思是: uri通用資源訪問符。在這裏MediaStore.Audio.Media.EXTERNAL_CONTENT_URI projection返回信息的行,用一個數組去設置要返回哪些行的信息 selection篩選條件 selectionArgs篩選條件的參數 sortOrder排序的順序 這個用默認的就好了MediaStore.Audio.Media.DEFAULT_SORT_ORDER
關鍵代碼
           public void loadSongFromSQL(){
		Cursor cursor=  getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MusicManager.media_info, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		
		cursor.moveToFirst();
		
		
		//遊標遍歷數據庫
		for(int i=0;i<cursor.getCount();i++){
			Song song=new Song();
			song.setTitle(cursor.getString(0));
			song.setArtist(cursor.getString(2));
			song.setDuration(Integer.parseInt(cursor.getString(1)));
			song.setId(cursor.getInt(3));
			song.setPath(cursor.getString(5));
			//增加song到MusicManager
			MusicManager.getInstance().addSong(song);
			
			
	 
			
			cursor.moveToNext();
		}

		//關閉遊標
		cursor.close();
	} 

存放歌曲信息的類
Song.java
package com.huwei.sweetmusicplayer.models;

import java.io.Serializable;

import com.huwei.sweetmusicplayer.util.CharacterParser;
import com.huwei.sweetmusicplayer.util.TimeUtil;

public class Song implements Serializable{
	private String title;	//歌曲名
	private int duration;	//時長
	private String artist;		//藝術家
	private int id;	//id
	private String display_name;
	private String data;
	private String date_added;
	
	private String path;		//歌曲路徑
	private String sortLetters;	    //檢索的首字母
 

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDisplay_name() {
		return display_name;
	}

	public void setDisplay_name(String display_name) {
		this.display_name = display_name;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}


	public String getDate_added() {
		return date_added;
	}

	public void setDate_added(String date_added) {
		this.date_added = date_added;
	}

	public Song(){
		
	}
	
	public Song(String title){
		super();
		this.title=title;
		
		if(title.equals("安居客")) 
			{
			System.out.println();
			}
		
		String firstLetter=CharacterParser.getFirstLetter(title);
		//正則匹配 ,匹配大寫和小寫字母
		if(firstLetter.matches("^[a-zA-Z]$")){
			this.sortLetters=firstLetter.toUpperCase();
		}else{
			this.sortLetters="#";
		}
	}
	
	public Song(String title, String sortLetters) {
		super();
		this.title = title;
		this.sortLetters = sortLetters;
	}


 
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getSortLetters() {
		return CharacterParser.getFirstUpperLetter(title);
	}
	public void setSortLetters(String sortLetters) {
		this.sortLetters = sortLetters;
	}

 

	public String getDurationTime(){
		return TimeUtil.toTime(duration);
	}

	public int getDuration() {
		return duration;
	}

	public void setDuration(int duration) {
		this.duration = duration;
	}

	public String getArtist() {
		return artist;
	}

	public void setArtist(String artist) {
		this.artist = artist;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	
} 

在Splash界面從數據庫讀入歌曲信息,然後在創建
SongsFragment時載入歌曲信息。

二,A-Z檢索功能:


至於SongsFragment的a-z檢索功能,先來講講思路,每次得到歌曲名,去獲取它的首字母,首字母的獲取能夠依據ansi編碼。 提取第一個字母,得到它的gb2312編碼的byte數組,英文占一個字節,中文占兩個字節。依據byte數組的長度,所以非常easy推斷第一個字符是英文還是中文。

1。英文 能夠直接獲取ansi值 2,中文 相應的拼音會相應一個值,比方 "a", "ai", "an", "ang"分別相應-20319, -20317, -20304, -20295,容我解釋一下。a發音的字符是-20319到-20318,而ai的發音是-20317到-20303。
這些奇怪的負數代表什麽呢?依據gb2312編碼,漢字由區碼(高字節)+位碼(低字節)表示。 1)區碼:high 01-09區為特殊符號。 16-55區為一級漢字。按拼音排序。 56-87區為二級漢字,按部首/筆畫排序。

10-15區及88-94區則未有編碼。 0xA1-0xF7(把01-87區的區號加上0xA0)
2)位碼:low 就是該分區的第幾個漢字 0xA1-0xFE(把01-94加上 0xA0)
比方漢字“啊”,按拼音排序的話,屬於16區的第一個字,區碼是0xB0(16進制的表示),位碼是0xA1,所以區碼加位碼表示0xB0A1
所以表示該漢字為256*high+low
而上面-20319就是 (256*high+low)-256*256,為什麽負數表示呢?我猜想是避免不必要的沖突吧。

詳細解析代碼:

//單個漢字轉成ansi
	public static int getChsAscii(String chs){
		int asc=0;
		
		try {
			byte[] bytes=chs.getBytes("gb2312");
			
			if(bytes==null||bytes.length==0){
				throw new RuntimeException("illegal resource string");
			}
			
			if(bytes.length==1){	//英文字符
				asc=bytes[0];
			}
			
			if(bytes.length==2){	//中文字符
				int highByte=256+bytes[0];
				int lowByte=256+bytes[1];
				
				asc=(256*highByte+lowByte)-256*256;	
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return asc;
	}
詳細解析的CharacterParser.java
package com.huwei.sweetmusicplayer.util;

import java.io.UnsupportedEncodingException;
 
/*
 * java漢字轉拼音*/
public class CharacterParser {
	//private static LinkedHashMap<String, Integer> spellMap;;
	private static int[] pyvalue = new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,  
        -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,  
        -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,  
        -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,  
        -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,  
        -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,  
        -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,  
        -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,  
        -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,  
        -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,  
        -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,  
        -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,  
        -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,  
        -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,  
        -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,  
        -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,  
        -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,  
        -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,  
        -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,  
        -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,  
        -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,  
        -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,  
        -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,  
        -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};  
public static String[] pystr = new String[] {"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",  
        "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",  
        "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",  
        "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",  
        "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",  
        "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",  
        "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",  
        "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",  
        "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",  
        "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",  
        "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",  
        "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",  
        "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",  
        "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",  
        "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",  
        "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",  
        "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",  
        "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",  
        "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",  
        "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",  
        "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",  
        "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};  
	
	
	private static CharacterParser instance;
	
 
	
	private StringBuilder resource;
	//單例模式
	public CharacterParser getInstance(){
		if(instance==null) {
			instance=new CharacterParser();
 
		}
			return instance;
	}
	
	public StringBuilder getResource() {
		return resource;
	}


	public void setResource(StringBuilder resource) {
		this.resource = resource;
	}

 
	
	//單個漢字轉成ansi
	public static int getChsAscii(String chs){
		int asc=0;
		
		try {
			byte[] bytes=chs.getBytes("gb2312");
			
			if(bytes==null||bytes.length==0){
				throw new RuntimeException("illegal resource string");
			}
			
			if(bytes.length==1){	//英文字符
				asc=bytes[0];
			}
			
			if(bytes.length==2){	//中文字符
				int highByte=256+bytes[0];
				int lowByte=256+bytes[1];
				
				asc=(256*highByte+lowByte)-256*256;	
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return asc;
	}
 
	
	//首字符是否是字母
	//大寫return 1 小寫return -1 非retrun 0
	public static int firstIsLetter(String name){
		int asc=getChsAscii(name.substring(0,1));
		if( asc>='A'&&asc<='Z'){//單字符
			return 1;
		}else if(asc>='a'&&asc<='z'){
			return -1;
		}else{
			return 0;
		}
		 
	}
	
	//提取首字母,大寫和小寫均可
	public static String getSpellByAscii(int asc){
		String res=null;
		if(asc>0&&asc<160){//單字符
			res=String.valueOf((char)asc);
		}
		else if (asc< -20319 || asc > -10247) { //未知字符
	           return null;
	    }  
	  
 
		else {
			for(int i=pyvalue.length-1;i>=0;i--){
				if(asc>=pyvalue[i]){
					res=pystr[i];
					break;
				}
			}
		}
		
		//提取首字母
		res=res.substring(0,1);
		
 
 
	    return res;
	}
	//獲取首字母的大寫字母
	public static String getFirstUpperLetter(String cn){
		return getFirstLetter(cn).toUpperCase();
	}
	
	
	//獲取首字母
	public static String getFirstLetter(String cn){
		return getSpellByAscii(getChsAscii(cn.substring(0, 1)));
	}
	
	//獲取全拼
	public static String getFullSpell(String cn){
		String resString=null;
		for(int i=0;i<cn.length();i++){
			String string=cn.substring(i, i+1);
			resString+=getSpellByAscii(getChsAscii(string));
		}
		return resString;
	}

}

然後把首字母同樣的列表項排在一起。在顯示的僅顯示第一個。



見下圖 比方七號公園。七裏香。七夕。。。僅僅顯示七號公園中的catalog。其它兩個隱藏。
列表項布局文件song_listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:descendantFocusability="afterDescendants"
    android:orientation="vertical" >

    <!-- 顯示字母項 -->

    <TextView
        android:id="@+id/catalog"
        style="@style/catalog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="catalog"
        android:visibility="gone" />

    <RelativeLayout
        android:id="@+id/song_item"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@drawable/effect_list_item_bg"
        android:clickable="true"
        android:focusable="true" >

        <TextView
            android:id="@+id/song_title"
            style="@style/song_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:maxEms="20"
            android:text="song_text"
            android:textSize="@dimen/text_size_medium" />

        <TextView
            android:id="@+id/duration_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="14dp"
            android:text="00:00"
            android:textColor="@color/darkgray" />

        <TextView
            android:id="@+id/artist_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_margin="10dp"
            android:text="artist_tv"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="@color/darkgray" />

        <View
            android:id="@+id/selected_view"
            android:layout_width="8dp"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@color/darkorchid"
            android:visibility="invisible" />
    </RelativeLayout>

</LinearLayout>



詳細控件代碼解釋能夠參考: http://blog.csdn.net/xiaanming/article/details/12684155

三,選中歌曲特效

技術分享


如今的問題是,當我點擊“七號公園”,焦點卻在整個listitem上,字母q和七號公園是一個總體,我們必需要屏蔽Listitem的焦點,而讓焦點在song_item這個相對布局上。 我們須要在最外層布局LinearLayout加上一個屬性。 android:descendantFocusability="afterDescendants",以致子控件優於viewgroup獲取焦點。

android:descendantFocusability屬性的值有三種:

beforeDescendants:viewgroup會優先其子類控件而獲取到焦點

afterDescendants:viewgroup僅僅有當其子類控件不須要獲取焦點時才獲取焦點

blocksDescendants:viewgroup會覆蓋子類控件而直接獲得焦點

然後這個紫色的小方塊並非一個背景,最開始我也想用一個背景來實現,後來參考了字母的實現方案,在選中時顯示這個方塊,未選中時隱藏這個方塊就好了。


樓主在實現的過程中,遇到一個小問題,特此記錄一下。 最開始是這樣寫的,比方要顯示紫色方塊。就在onSelecte()後,立即設置為控件的setVisibility(),後來發現把這個歌曲滑到看不見位置。然後又滑下來,發現設置的效果不起作用了。

後來思考了下。由於再把歌曲滑下來,會去調用listView的adapter的getView(),所以setVisibility()就不起作用了。建議寫出以下這樣。用一個selectedpos去標記選中的位置,然後在getView()設置屬性。 所以選中後。刷新一下listView就好了。

                //設置正在播放的音樂的視圖(紫色小方塊)
		int selectedpos=MusicManager.getInstance().getNowplaying_index();
		if(position==selectedpos){
			mViewHolder.selected_view.setVisibility(View.VISIBLE);
		}else{
			mViewHolder.selected_view.setVisibility(View.INVISIBLE);
		}
下一篇總結播放本地音樂: http://blog.csdn.net/huweigoodboy/article/details/39861539

android音樂播放器開發 SweetMusicPlayer 載入歌曲列表