Skip to content

Instantly share code, notes, and snippets.

@jmatsu
Last active August 29, 2015 14:13
Show Gist options
  • Save jmatsu/4ed652093af8f6fef3a7 to your computer and use it in GitHub Desktop.
Save jmatsu/4ed652093af8f6fef3a7 to your computer and use it in GitHub Desktop.
This handles audio tracks on Android devices.
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jmatsu on 2014/10/21.
*/
public class AudioSample {
private AudioSample(){}
private static final String[] COLUMNS = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.TRACK,
};
public static List<Track> getTracks(Context activity) {
List tracks = new ArrayList();
ContentResolver resolver = activity.getContentResolver();
Cursor cursor = resolver.query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
COLUMNS,
null,
null,
null
);
while (cursor.moveToNext()) {
if (cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)) < 3000) {
continue;
}
tracks.add(new Track(cursor));
}
cursor.close();
return tracks;
}
public static class Track {
public long id; // unique id from content provider
public long albumId; // album id from content provider
public long artistId; // artist id of the album from content provider
public String path; // file path
public String title; // the title of the track
public String album; // the title of the album
public String artist; // the name of the artist
public Uri uri; // uri
public long duration; // playing duration
public int trackNo; // track number (not id)
Track(Cursor cursor) {
id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
artistId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
trackNo = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment