1、获取音乐
1-1:获取手机中的音乐(用ContentProvider内容提供者来完成):
1 package com.firefly.util; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import android.content.Context; 9 import android.database.Cursor; 10 import android.provider.MediaStore; 11 import android.util.Log; 12 13 public class MediaUtil { 14 /** 15 * 用于从数据库中查询歌曲的信息,保存在List当中 16 * 17 * @return 18 */ 19 public static List<Mp3Info> getMp3Infos(Context context) { 20 Cursor cursor = context.getContentResolver().query( 21 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, 22 MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 23 List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>(); 24 25 for (int i = 0; i < cursor.getCount(); i++) { 26 cursor.moveToNext(); 27 Mp3Info mp3Info = new Mp3Info(); 28 long id = cursor.getLong(cursor 29 .getColumnIndex(MediaStore.Audio.Media._ID)); // 音乐id 30 String title = cursor.getString((cursor 31 .getColumnIndex(MediaStore.Audio.Media.TITLE))); // 音乐标题 32 String artist = cursor.getString(cursor 33 .getColumnIndex(MediaStore.Audio.Media.ARTIST)); // 艺术家 34 long duration = cursor.getLong(cursor 35 .getColumnIndex(MediaStore.Audio.Media.DURATION)); // 时长 36 long size = cursor.getLong(cursor 37 .getColumnIndex(MediaStore.Audio.Media.SIZE)); // 文件大小 38 String url = cursor.getString(cursor 39 .getColumnIndex(MediaStore.Audio.Media.DATA)); // 文件路径 40 int isMusic = cursor.getInt(cursor 41 .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC)); // 是否为音乐 42 if (isMusic != 0) { // 只把音乐添加到集合当中 43 44 mp3Info.setId(id); 45 mp3Info.setTitle(title); 46 mp3Info.setArtist(artist); 47 mp3Info.setDuration(duration); 48 mp3Info.setSize(size); 49 mp3Info.setUrl(url); 50 51 mp3Infos.add(mp3Info); 52 } 53 } 54 return mp3Infos; 55 } 56 57 /** 58 * 格式化时间,将毫秒转换为分:秒格式 59 * 60 * @param time 61 * @return 62 */ 63 public static String formatTime(long time) { 64 String min = time / (1000 * 60) + ""; 65 String sec = time % (1000 * 60) + ""; 66 if (min.length() < 2) { 67 min = "0" + time / (1000 * 60) + ""; 68 } else { 69 min = time / (1000 * 60) + ""; 70 } 71 if (sec.length() == 4) { 72 sec = "0" + (time % (1000 * 60)) + ""; 73 } else if (sec.length() == 3) { 74 sec = "00" + (time % (1000 * 60)) + ""; 75 } else if (sec.length() == 2) { 76 sec = "000" + (time % (1000 * 60)) + ""; 77 } else if (sec.length() == 1) { 78 sec = "0000" + (time % (1000 * 60)) + ""; 79 } 80 return min + ":" + sec.trim().substring(0, 2); 81 } 82 }