How to get list of all music files from android phone

时间:2017-11-13 06:11:00

标签: android android-sdcard audio-player android-music-player

I created an app that scans music files on the mobile phone. It scans the music files if I scan the folder /sdcard/Music but it doesn't scan the mp3 file when I write /sdcard. It is working fine. But it is not working on some devices, the application crashes maybe because of that path not present on that phone what should I do?

CODE

public class SongsManager {

// SDCard Path
  String MEDIA_PATH = new String("/sdcard/Music");
 private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 */ public ArrayList<HashMap<String, String>> getPlayList(){
       File home = new File(MEDIA_PATH);


    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            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
    return songsList;
}

class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}

}

1 个答案:

答案 0 :(得分:1)

//Retrieve a list of Music files currently listed in the Media store DB via URI.

//Some audio may be explicitly marked as not being music

String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

String[] projection = {
    MediaStore.Audio.Media._ID,
    MediaStore.Audio.Media.ARTIST,
    MediaStore.Audio.Media.TITLE,
    MediaStore.Audio.Media.DATA,
    MediaStore.Audio.Media.DISPLAY_NAME,
    MediaStore.Audio.Media.DURATION
};

cursor = this.managedQuery(
    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
    projection,
    selection,
    null,
    null);

private List<String> songs = new ArrayList<String>();
while(cursor.moveToNext()){
    songs.add(cursor.getString(0) + "||" + cursor.getString(1) + "||" +   cursor.getString(2) + "||" +   cursor.getString(3) + "||" +  cursor.getString(4) + "||" +  cursor.getString(5));
}