List All Mp3 files in android
Asked Answered
V

4

6

I am developing music player in android but stuck in reading MP3 files. here is my code to read all mp3 files. but its not returing any files from device(although there are some files which i copied using adb). I also want it to list using Album, artist etc. please help in this.

final String MEDIA_PATH = Environment.getExternalStorageDirectory()+"";

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) {
    if (home.listFiles(new FileExtensionFilter())!=null) {

        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 to filter files which are having .mp3 extension
 * */
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}
Valeriavalerian answered 13/9, 2016 at 3:52 Comment(6)
try this https://mcmap.net/q/1630525/-android-studio-music-player-cant-read-from-sdcard-only-internal-memory , from this link you will find how to get the file with ".mp3" from both phone memory and sdCard memory. hope this will help youMason
If you want to list the songs as Album (or) Artist wise. you should you MediaStore ContentProvider. here is an official doc developer.android.com/reference/android/provider/…Mason
hi @Mason thank you for mesg, i try this but same.. can you plz help me on this.Valeriavalerian
did you add READ_EXTERNAL_STORAGE and READ_INTERNAL_STORAGE permission in your manifest file?Mason
just tried that also.<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Valeriavalerian
check my answerMason
M
17

here I've modified your getPlayList() method. look into it.

ArrayList<HashMap<String,String>> getPlayList(String rootPath) {
            ArrayList<HashMap<String,String>> fileList = new ArrayList<>();


            try {
                File rootFolder = new File(rootPath);
                File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains  any file,handle it like this.
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (getPlayList(file.getAbsolutePath()) != null) {
                            fileList.addAll(getPlayList(file.getAbsolutePath()));
                        } else {
                            break;
                        }
                    } else if (file.getName().endsWith(".mp3")) {
                        HashMap<String, String> song = new HashMap<>();
                        song.put("file_path", file.getAbsolutePath());
                        song.put("file_name", file.getName());
                        fileList.add(song);
                    }
                }
                return fileList;
            } catch (Exception e) {
                return null;
            }
        }

you can get the song name and song path like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ArrayList<HashMap<String,String>> songList=getPlayList("/storage/sdcard1/");
        if(songList!=null){
        for(int i=0;i<songList.size();i++){
        String fileName=songList.get(i).get("file_name");
        String filePath=songList.get(i).get("file_path");
        //here you will get list of file name and file path that present in your device
        log.e("file details "," name ="+fileName +" path = "+filePath);
        }
        }
    }

Note: use "/storage/sdcard1/" for reading files from sdCard and use Environment.getExternalStorageDirectory().getAbsolutePath() for reading files from phone memory

Hope this will help you.

Mason answered 13/9, 2016 at 7:20 Comment(6)
thank you so much man. its works for me. and you have saved my so many hours... thank you once again.Valeriavalerian
Hi @Mason Again i am troubling you. Can we restrict recursive till 3 or 5 folders. Its looping to all sub folders and its taking so much time. i tried to stop after 3 folers search buts its not working. Thank you.Valeriavalerian
If it takes too much of time to fetch all your data means then run this method in the separate thread. don't restrict it without having any valid reason. you can use AsyncTask class to solve this issueMason
yes we can make it on seprrate thread but i want to restrict scan till 5 sub folders. becouse we never know how many sub folders are there on users devices. so i want to make recursive function loop till 5 folders. after that it should return to next folder.Valeriavalerian
yes, you can. make an int variable outside the getPlayList() method. and increment this int variable once it enters the if (file.isDirectory()) { block, before that you should check. is the int variable is less than 5 to proceed the if (file.isDirectory()) { blockMason
Let us continue this discussion in chat.Valeriavalerian
N
9

Hope you already found your answer but may be this is better and if you wants to try, Here is your solution use the following code to Read the MP3 file from the Specific Folder or All files,

First of all Create 1 Model class as Given Below, to GET and SET Files in list.

AudioModel.class

public class AudioModel {

    String aPath;
    String aName;
    String aAlbum;
    String aArtist;

    public String getaPath() {
        return aPath;
    }

    public void setaPath(String aPath) {
        this.aPath = aPath;
    }

    public String getaName() {
        return aName;
    }

    public void setaName(String aName) {
        this.aName = aName;
    }

    public String getaAlbum() {
        return aAlbum;
    }

    public void setaAlbum(String aAlbum) {
        this.aAlbum = aAlbum;
    }

    public String getaArtist() {
        return aArtist;
    }

    public void setaArtist(String aArtist) {
        this.aArtist = aArtist;
    }
}

Now We have our Model Class, use the below code to Read the all MP3 files from your Folder or device.

This will return list of all MP3 Files with Music NAME, PATH, ARTIST, ALBUM. if you want more details, please refer the documentation for Media.Store.Audio

public List<AudioModel> getAllAudioFromDevice(final Context context) {

        final List<AudioModel> tempAudioList = new ArrayList<>();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST,};
        Cursor c = context.getContentResolver().query(uri, projection, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%yourFolderName%"}, null);

        if (c != null) {
            while (c.moveToNext()) {

                AudioModel audioModel = new AudioModel();
                String path = c.getString(0);
                String album = c.getString(1);
                String artist = c.getString(2);

                String name = path.substring(path.lastIndexOf("/") + 1);

                audioModel.setaName(name);
                audioModel.setaAlbum(album);
                audioModel.setaArtist(artist);
                audioModel.setaPath(path);

                Log.e("Name :" + name, " Album :" + album);
                Log.e("Path :" + path, " Artist :" + artist);

                tempAudioList.add(audioModel);
            }
            c.close();
        }

        return tempAudioList;
    }

To read the files of a specific folder, use this query (write the target folder name in the query)

Cursor c = context.getContentResolver().query(uri,
                                          projection, 
                                          MediaStore.Audio.Media.DATA + " like ? ", 
                                          new String[]{"%yourFolderName%"}, // yourFolderName 
                                          null);

If you want all the files on the device, use this query:

Cursor c = context.getContentResolver().query(uri,
                                          projection, 
                                          null, 
                                          null, 
                                          null);

Don't forget to add the storage permission.

Nonet answered 30/9, 2016 at 6:48 Comment(6)
Wow thanks this is super fast , will the last query give the files in sdcard ?Philippa
Change this line to fetch data from diff director : Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;Nonet
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI alone is enough i guess , its listing from both internal and sdcardPhilippa
Yeah, only mentioned to inform that you can change it!Nonet
Awesome brother. Thanks a lot.Tigrinya
In MI phones if i place mp3 file to Pictures folder then it is not working . Also it does not return recordings with .mp3 extensionsAccrue
T
4

Try This

String path;
File sdCardRoot = Environment.getExternalStorageDirectory();
File dir = new File(sdCardRoot.getAbsolutePath() + "/yourDirectory/");

if (dir.exists()) {

    if (dir.listFiles() != null) {
        for (File f : dir.listFiles()) {
            if (f.isFile())
                path = f.getName();

            if (path.contains(".mp3")) {
                yourArrayList.add(path);

            }
        }
    }
}
Twist answered 13/9, 2016 at 5:1 Comment(5)
not working. geting null value in here dir. if (dir.listFiles() != null) {Valeriavalerian
that means there is no mp3 file in that folder...try changing the folder name and check if dir is null or notTwist
@kushalPatil wants to display all the files from the phone, not in a particular folder. so this logic doesn't work.Mason
see this link https://mcmap.net/q/1630525/-android-studio-music-player-cant-read-from-sdcard-only-internal-memory to parse all the files from both the phone and sdCard memory.Mason
@Twist i have mp3 files in my device and emulator, then also its not showing. is i need to give full MP3 folder path. cant it read all device and search for .mp3Valeriavalerian
C
1

This function will provide you a list of all audio files paths in device storage

 public ArrayList<String> getAllMusic(){
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.Audio.AudioColumns.DATA};
    ArrayList<String> songs_path = new ArrayList<>();
    Cursor c = context.getContentResolver().query(uri, projection, null,null,null);

    if (c != null) {
        while (c.moveToNext()) {

            String path = c.getString(0);
            songs_path.add(path);
        }
        c.close();
    }

    return songs_path;
}


ArrayList<String> allSongs = getAllMusic();

File song = new File(allSongs.get(0));
Carsick answered 26/5, 2022 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.