I am trying to get a song from a playlist then play it in android.
All answers i can find relies on
MediaStore.MediaColumn.DATA
to find the file path and then feed it to the MediaPlayer.
But when i tried to do it, i kept getting "invalid column _data" exception.I can still query for other stuff about the song, like the "AUDIO_ID". So my question is, is it possible to play the song with only the "AUDIO_ID" known? How? Or is there something that i am missing for the "data", since every other people are able to use it.
This is my code for getting playlist.
private Cursor getPlaylistCursor() {
String[] proj = { MediaStore.Audio.Playlists._ID,MediaStore.Audio.Playlists.NAME };
Uri playlistUri = Uri.parse("content://com.google.android.music.MusicConten/playlists");
Cursor playlistCursor = getContentResolver().query(playlistUri, proj,null, null, null);
playlistCursor.moveToFirst();
return playlistCursor;
}
This is what i am working on for getting song, as i said, i cannot query the "data", if the "data" argument is added to the projection, i get an exception.
private void getSongListCursor(Long playlistID) {
String[] proj2 = { MediaStore.Audio.Playlists.Members.TITLE,
MediaStore.Audio.Playlists.Members.AUDIO_ID };
String playListRef = "content://com.google.android.music.MusicContent/playlists/"
+ playlistID + "/members";
Uri songUri = Uri.parse(playListRef);
Cursor songCursor = getContentResolver().query(songUri, proj2, null,
null, null);
}
SO now, i have the audio ID of a song, how do i play it?
Everything is possible ;-)
My approach is to use the Google Play Music server to obtain the streaming URL corresponding to the selected song ID. Just let me know if you need help with authentication and jump-start with the unofficial API for Google Play Music.
Related
I'm writing an app that can play all audio files present in MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.
Here's a bit of what I have so far:
String[] projection = {MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DATA};
Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null);
while (cursor.moveToNext()) {
String uri = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
// Use uri to play music...
}
And this works fine. I'm able to play the audio by passing the uri to a MediaPlayer.
However...
MediaStore.Audio.Media.DATA has no guarantees of holding a uri. To my understanding, it can hold absolutely anything.
MediaStore.Audio.Media.DATA is deprecated.
Is there any way to play the audio items in external storage, without relying on MediaStore.Audio.Media.DATA?
Yes, it is.
You can simply play it with the ContentUris.withAppendedId, as MediaPlayer has a method for playing content by Uri.
Here, for example, i'm setting the song Uri.
/// Helper function
public static Uri getSongUri(int songId) {
return ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songId);
}
/// And then...
public void setUri(Context appContext, int songId) {
// ....
player.setDataSource(appContext, getSongUri(songId));
// ....
}
Using this method of audio file retrieval from Android's external storage
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
can I actually find a resonable way to fetch a genre of the given song? MediaStore class seems to provide everything else - from song's title to its composer info - except for the genre field. Should I use MediaMetadataRetriever then? If so, how drastically can creating a MediaMetadataRetriever instance for every song on a device reduce app's performance?
Maybe there are some better ways to retrieve all audio files from both external and internal storages in android?
As mentioned at Developer's Site,
You can fetch the Genres of the Audio file using MediaStore.Audio.Genres
Sample Code :
private static String[] genresProj = {
MediaStore.Audio.Genres.NAME,
MediaStore.Audio.Genres._ID
};
int idIndex = cursor
.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
while (cursor.moveToNext()){
int id = Integer.parseInt(mediaCursor.getString(idIndex));
Uri uri = MediaStore.Audio.Genres.getContentUriForAudioId("external", id );
genresCursor = context.getContentResolver().query(uri,
genresProj , null, null, null);
int genreIndex = genresCursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
while (genresCursor.moveToNext()) {
Log.d(TAG, "Genre = " +genresCursor.getString(genreIndex));
}
}
}
To fetch other details of the Audio file, please check here .
I'm creating a music player that populates an array list with song objects. Each song object has a series of attributes. One of those attributes is the album-art URI.
This is the line of code where I assign the URI attribute to the song object.
songObject.albumArtURI = GetAlbumArtURI(albumID);
Here is the string value of albumID
Log.v("TAG",String.valueOf(albumID)); // prints [Ljava.lang.String;#44ce53d
When I pass albumID to GetAlbumArtURI() method
private String GetAlbumArtURI(String[] albumID){
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums.ALBUM_ID + "=?",
albumID, // Error
null
);
return mCursor.getString(0);
}
I get this error:
no such column: album_id (code 1)
while compiling:
SELECT album_art FROM album_info WHERE (album_id=?)
The error essentially says that table album_info does not contain album_id column. But according to the documenation, album_info does have such a column.
So there's a few issues causing your query to return nothing and throw that error.
MediaStore.Audio.Albums.ALBUM_ID is not the column you want to reference. You should be using MediaStore.Audio.Albums._ID.
You need to move your cursor's read position to the first position when you get results, if possible. Doing otherwise will result in you never getting the results you need
The way that MediaStore works on android is that you have to register the media files that you want the OS to know about - this isn't automatic. You need to implement something similar to the SingleMediaScanner described in this thread
Here is the working bit of code that I have written:
try {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
null,
null
);
// You need to check if there are results in your cursor.
// This is like saying if(mCursor.getCount() > 0)
if(mCursor.moveToFirst()) {
return mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
} else {
return "";
}
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(),e.getMessage());
}
When you have called that code, you're assuming that the MediaStore on your device knows about the music files you've downloaded or added. You can definitely implement a BroadcastReceiver to capture system events like files being added, but for this answer I'm just going to show how you account for one known file. You could also expand this to search an entire directory by adding to the onMediaScannerConnected(...) method.
If you implement the SingleMediaScanner file found here you can then just do:
File file = new File(Environment.getExternalStorageDirectory() + "/Download/1.mp3");
SingleMediaScanner singleMediaScanner = new SingleMediaScanner(this, file);
And it will register the media file in your MediaStore. At that point, you should be able to get results back from your query above. If you are having doubts of whether or not the songs are being registered, you can check to see if any records have been added at all by changing your mCursor call to this (to get all the results in the media store) and then iterating through them:
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
null,
null,
null,
null
);
I have videoplayer app with filebrowser listing all videos on SD card
Code inspired by i want get audio files in sd card
Using ContentResolver, works as expected, but it does not update if the files on card change. I do not mean automatically, but after view/app restart. Not even reinstalling the application helped, still shows the same files. The deleted video file is not visible via PC nor it is possible to play it (This video cannot be played (translation)).
I dumped the data and the problem is not in view caching or elsewhere. I do not implement any caching of my own and failed to find anything on the matter. Thank you
Code:
// acquisition
String[] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.DATA
};
ContentResolver resolver = getActivity().getContentResolver();
Cursor videoCursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null
);
// extraction
while(cursor.moveToNext()) {
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
filepath = cursor.getString(cursorIndex);
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
filename = cursor.getString(cursorIndex);
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
duration = cursor.getString(cursorIndex);
result[ index++ ] = new VideoFileMetadata(filename, duration, filepath);
}
Edit 1 [14-03-2013]:
I tried adding number + " = " + number to ORDER or WHERE clause to act as a potential query caching buster, but it had no effect (although it's possible it was removed by an optimizer as a useless clause). This time I had reinstalled the application from a different machine using different certificate, but the query result remained the same, listing currently non-existing files.
You should first call cursor.moveToFirst() .
So, your cursor iteration loop should look like
if (cursor.moveToFirst()) {
do {
// cursorIndex = cursor.getColumnIndexOrThrow, etc...
} while (cursor.moveToNext());
}
A project I'm currently working on requires the application to discover all audio tracks on an android device. In addition to the tracks, it must also be able to group them by album and artist.
I found the MediaStore content provider and set about creating a database helper utility class to quickly return the IDs of tracks, albums and artists. I have been able to query the Media Store which returns some result, but it appears that not all of the audio information is stored there.
For example, querying for all artists returns only 9 results, but the Android Music Player application returns 27.
I am using the following code to query the artists:
ContentResolver resolver = getContentResolver();
String[] projection = new String[]{MediaStore.Audio.ArtistColumns.ARTIST};
Uri uri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor c = null;
try {
c = resolver.query(uri, projection, null, null, null);
}
catch (UnsupportedOperationException e) {
Log.e("DatabaseHelper", "query: " + e);
c = null;
}
if(c != null) {
while(c.isAfterLast() == false) {
Log.e("ARTIST", "NAME: " + cursor.getString(0));
cursor.moveToNext();
}
}
It seems as if the Media Scanner (which is definatley run when my device boots up) is not detecting much of my audio library. Am I doing something wrong?
I am simply trying to find all audio tracks, audio albums and audio artists quickly and efficiently. If MediaStore can't help me then I fear I will have to implement some form of file scanner to traverse directory structures and build my own database, but I don't want to do that ;)
Any thoughts would be much appreciated.
Thanks.
Probably, You should also query android.provider.MediaStore.Audio.Albums.INTERNAL_CONTENT_URI to get the rest visible in media player.