Reputation: 33
I've created a playlist of 3 songs from within the "Music" app which came pre-installed on my device, and within my own app I've successfully queried MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI for it (checked the name in debug to make sure it's the correct playlist) and saved its id for when I need to start playing songs from it.
Later when I come to play one of those songs, the song count from the playlist is correct but it plays different tracks to those I put in the playlist. Here's the block of code which gets the tracks out of the playlist.
Note: This is within a PhoneGap plugin, so "this.ctx" is the Activity. My test device is a HTC Desire running Android 2.2, if that's of any relevance.
Cursor cursor = null;
Uri uri = null;
Log.d(TAG, "Selecting random song from playlist");
uri = Playlists.Members.getContentUri("external", this.currentPlaylistId);
if(uri == null) {
Log.e(TAG, "Encountered null Playlist Uri");
}
cursor = this.ctx.managedQuery(uri, new String[]{Playlists.Members._ID}, null, null, null);
if(cursor != null && cursor.getCount() > 0) {
this.numSongs = cursor.getCount();
Log.d(TAG, "numSongs: "+this.numSongs); // Correctly outputs 3
int randomNum = (int)(Math.random() * this.numSongs);
if(cursor.moveToPosition(randomNum)) {
int idColumn = cursor.getColumnIndex(Media._ID); // This doesn't seem to be giving me a track from the playlist
this.currentSongId = cursor.getLong(idColumn);
try {
JSONObject song = this.getSongInfo();
play(); // This plays whatever song id is in "this.currentSongId"
result = new PluginResult(Status.OK, song);
} catch (Exception e) {
result = new PluginResult(Status.ERROR);
}
}
}
Upvotes: 3
Views: 1735
Reputation: 63955
Playlists.Members._ID
is the id inside the playlist which can be used to sort the playlist
Playlists.Members.AUDIO_ID
is the ID of the audio file.
So your code should be like
cursor = this.ctx.query(uri, new String[]{Playlists.Members.AUDIO_ID}, null, null, null);
if(cursor != null && cursor.getCount() > 0) {
this.numSongs = cursor.getCount();
Log.d(TAG, "numSongs: "+this.numSongs); // Correctly outputs 3
int randomNum = (int)(Math.random() * this.numSongs);
if(cursor.moveToPosition(randomNum)) {
int idColumn = cursor.getColumnIndex(Playlists.Members.AUDIO_ID); // This doesn't seem to be giving me a track from the playlist
// or just cursor.getLong(0) since it's the first and only column you request
this.currentSongId = cursor.getLong(idColumn);
try {
JSONObject song = this.getSongInfo();
play(); // This plays whatever song id is in "this.currentSongId"
result = new PluginResult(Status.OK, song);
} catch (Exception e) {
result = new PluginResult(Status.ERROR);
}
}
}
Upvotes: 2