Search code examples
androidandroid-recyclerviewaudio-playerandroid-music-player

Best way to fetch Songs from SD Card


What is the best way to create Android music player? I've read various tutorials some were fetching using a custom method where it gathers all the files and the one with '.mp3' extension is added to the ArrayList()<> and some were using MediaStore. Which one is the best way?

If I use the recursive method every time the application is opened it perform its task and store the result in ArrayList()<>, this takes time, on the other hand, I didn't try the MediaStore approach. So is it the good one? Should I go for it?


Solution

  • You are right traversing through all the files in the storage system and storing relevant one is always a heavy task than to access a system specifically designed for particular task. Accessing MediaStore is a recommended way to get local media files. Please refer below code picked from one of our fellow community member page

     ContentResolver cr = getActivity().getContentResolver();
    
      Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
     String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
     String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
     Cursor cur = cr.query(uri, null, selection, null, sortOrder);
     int count = 0;
    
    if(cur != null)
    {
      count = cur.getCount();
    
    if(count > 0)
    {
        while(cur.moveToNext())
        {
            String data = cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA));
        int songId = cur.getColumnIndex(MediaStore.Audio.Media._ID);
        int songTitle = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
            // Add code to get more column here
    
            // Save to your list here
        }
    
    }
    }
    
     cur.close();