android音乐播放器开发 SweetMusicPlayer 载入歌曲列表

Posted clnchanpin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android音乐播放器开发 SweetMusicPlayer 载入歌曲列表相关的知识,希望对你有一定的参考价值。

上一篇写了播放器的总体实现思路,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 载入歌曲列表的主要内容,如果未能解决你的问题,请参考以下文章

Android开发本地及网络Mp3音乐播放器(十八)新下载歌曲加载准备SdcardSearchToList

Android开发---MediaPlayer简单音乐播放器

Android开发实战之简单音乐播放器

移动开发音乐播放器

android音乐播放器加载本地音乐失败

基于android的在线音乐播放器app设计