How To Get Audio Files From The Internal Storage In Android

159

In this blog post, we will use MediaStore.Audio class to retrieve our audio files from an Android device.

MediaStore.Audio is working like a container. It contains all the audio files from internal and external storage.

We will follow some basic steps to retrieve audio files-

  1. Get all the audio file from MediaStore.
  2. Add all the retrieved files in a List.
  3. Display the List.

1- Get Audio Files

We will use MediaStore.Audio file to retrieve the audio files from storage(internal or external).

First, we have to specify what are the contents we are going to retrieve, for that we will create an array of projections we need.

Here is the code flick for that-

String[] proj = {MediaStore.Audio.Media._ID,
       MediaStore.Audio.Media.TITLE,
       MediaStore.Audio.Media.ARTIST,
       MediaStore.Audio.Media.DURATION,
       MediaStore.Audio.Media.DATA,
       MediaStore.Audio.Media.ALBUM,
       MediaStore.Audio.Media.ALBUM_ID
};

Ok, we know what content we need, now set the projection and make a query for data, for that purpose we will use Cursor interface.

The cursor is very useful when you are retrieving some data from storage. It provides read-write access to the result set return by a query.

Here is the code flick for that-

Cursor audioCursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, selection, null, sortOrder);

2- Add result-set into a List

We have all the data access using above query. Now add that data into a list.

Here is the code flick for that-

if (audioCursor != null) {
   if (audioCursor.moveToFirst()) {
       do {
           int audioTitle = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
           int audioartist = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
           int audioduration = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION);
           int audiodata = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
           int audioalbum = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
           int audioalbumid = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
           int song_id = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
           Songfileinfo info = new Songfileinfo();
           info.setFile_uri(audioCursor.getString(audiodata));
           info.setTitle(audioCursor.getString(audioTitle));
           info.setDuration((audioCursor.getString(audioduration)));
           info.setArtist(audioCursor.getString(audioartist));
           info.setAlbum(audioCursor.getString(audioalbum));
           info.setId(audioCursor.getLong(song_id));
           info.setAlbum_art((ContentUris.withAppendedId(albumArtUri, audioCursor.getLong(audioalbumid))).toString());
           songList.add(info);
       } while (audioCursor.moveToNext());
   }
}


To get the album art we need to add

final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");

Here is the complete code of the class

public class Songdata {

   private ArrayList<Songfileinfo> songList = new ArrayList<>();
   final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");

   public ArrayList<Songfileinfo> getPlayList(Context context) {
       {

           try {
               String[] proj = {MediaStore.Audio.Media._ID,
                       MediaStore.Audio.Media.TITLE,
                       MediaStore.Audio.Media.ARTIST,
                       MediaStore.Audio.Media.DURATION,
                       MediaStore.Audio.Media.DATA,
                       MediaStore.Audio.Media.ALBUM,
                       MediaStore.Audio.Media.ALBUM_ID
               };

               Cursor audioCursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, selection, selectionArgs, null);

               if (audioCursor != null) {
                   if (audioCursor.moveToFirst()) {
                       do {
                           int audioTitle = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
                           int audioartist = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
                           int audioduration = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION);
                           int audiodata = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                           int audioalbum = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
                           int audioalbumid = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
                           int song_id = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
                           Songfileinfo info = new Songfileinfo();
                           info.setFile_uri(audioCursor.getString(audiodata));
                           info.setTitle(audioCursor.getString(audioTitle));
                           info.setDuration((audioCursor.getString(audioduration)));
                           info.setArtist(audioCursor.getString(audioartist));
                           info.setAlbum(audioCursor.getString(audioalbum));
                           info.setId(audioCursor.getLong(song_id));
                           info.setAlbum_art((ContentUris.withAppendedId(albumArtUri, audioCursor.getLong(audioalbumid))).toString());
                           songList.add(info);
                       } while (audioCursor.moveToNext());
                   }
               }
               assert audioCursor != null;
               audioCursor.close();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }


       return songList;
   }
}


Here is the songfileinfo class

public class Songfileinfo  {
   private String title, album, artist, file_uri;
   private String album_art, duration;
   public long id = 0;

   public long getId() {
       return id;
   }

   public void setId(long id) {
       this.id = id;
   }

   public Songfileinfo(Parcel in) {
       title = in.readString();
       album = in.readString();
       artist = in.readString();
       file_uri = in.readString();
       album_art = in.readString();
       id = in.readLong();
   }



   public String getDuration() {
       return duration;
   }

   public void setDuration(String duration) {
       this.duration = duration;
   }

   public String getTitle() {
       return title;
   }

   public void setTitle(String title) {
       this.title = title;
   }

   public String getAlbum() {
       return album;
   }

   public void setAlbum(String album) {
       this.album = album;
   }

   public String getArtist() {
       return artist;
   }

   public void setArtist(String artist) {
       this.artist = artist;
   }

   public String getFile_uri() {
       return file_uri;
   }

   public void setFile_uri(String file_uri) {
       this.file_uri = file_uri;
   }

   public String getAlbum_art() {
       return album_art;
   }

   public void setAlbum_art(String album_art) {
       this.album_art = album_art;
   }


}

3- Display List

Now it’s the time to display all the data into a View. For that, we have to create a ListView in the layout and then create an Adapter to bridge between View and program part.

Here is the code flick for that-

ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter arrayAdapter = new CustomeAdapter(this, audioList);
listView.setAdapter(arrayAdapter);


Here is how to call the class

public class MainActivity extends AppCompatActivity {
   private ArrayList<Songfileinfo> audioList = new ArrayList<>();

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       External();
       ListView listView = (ListView) findViewById(R.id.list);
       ArrayAdapter arrayAdapter = new CustomeAdapter(this, audioList);
       listView.setAdapter(arrayAdapter);
   }

   public void External() {
       Songdata load = new Songdata();
       this.audioList = load.getPlayList(this);
   }
}

Here is the custom adapter

public class CustomAdapter extends ArrayAdapter {
   private final Typeface typeface;
   public Customadapter(Context context, int custom_album_child, ArrayList<Songfileinfo> albumarr) {
       super(context, custom_album_child, albumarr);
       typeface = Typeface.createFromAsset(context.getAssets(), "font.ttf");
   }

   @NonNull
   @Override
   public View getView(int position, View convertView, @NonNull ViewGroup parent) {
       View view = convertView;
       LayoutInflater layoutInflater = LayoutInflater.from(getContext());
       if (convertView == null) {
           view = layoutInflater.inflate(R.layout.custom_album_child, parent, false);
       }
       Songfileinfo songfileinfo = (Songfileinfo) getItem(position);
       TextView textView = (TextView)view.findViewById(R.id.textView12);
       TextView textView1 = (TextView)view.findViewById(R.id.albumchild_sub);
       TextView textView2 = (TextView)view.findViewById(R.id.albumchild_sub1);

       if (songfileinfo != null) {
           textView.setText(songfileinfo.getTitle());
           textView.setTypeface(typeface);
       }
       if (songfileinfo != null) {
           textView1.setText(songfileinfo.getArtist());
           textView1.setTypeface(typeface);
       }
       long timer = 0;

       if (songfileinfo != null) {
           timer = Long.parseLong(songfileinfo.getDuration());
           textView2.setText(""+milliSecondsToTimer(timer));
           textView2.setTypeface(typeface);
       }


       return view;
   }
   public String milliSecondsToTimer(long milliseconds) {
       String finalTimerString = "";
       String secondsString = "";

       // Convert total duration into time
       int hours = (int) (milliseconds / (1000 * 60 * 60));
       int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
       int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
       // Add hours if there
       if (hours > 0) {
           finalTimerString = hours + ":";
       }

       // Prepending 0 to seconds if it is one digit
       if (seconds < 10) {
           secondsString = "0" + seconds;
       } else {
           secondsString = "" + seconds;
       }

       finalTimerString = finalTimerString + minutes + ":" + secondsString;

       // return timer string
       return finalTimerString;
   }

}