Android: MediaStore is missing artists and albums - android

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.

Related

Is there any way to fetch song's genre using MediaStore?

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 want to prevent my music player app to scan the directories for audio files everytime the app launches. How can I do that?

I want to prevent my music player app from scanning the directories for audio files everytime the app launches. How can I do that?
I have been using the following code to scan the audio files.
public void getSongList() {
ContentResolver contentResolver=getContentResolver();
Uri musicUri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = contentResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumIDColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
long thisAlbumID=musicCursor.getLong(albumIDColumn);
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Bitmap albumArtBitMap=null;
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisAlbumID);
try {
albumArtBitMap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), albumArtUri);
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, albumArtBitMap.getWidth(), albumArtBitMap.getHeight()), new RectF(0, 0, 300, 300), Matrix.ScaleToFit.CENTER);
albumArtBitMap = Bitmap.createBitmap(albumArtBitMap, 0, 0, albumArtBitMap.getWidth(), albumArtBitMap.getHeight(), m, true);
} catch (IOException e) {
e.printStackTrace();
}
songList.add(new Song(thisId, thisTitle, thisArtist,albumArtBitMap));
}
while (musicCursor.moveToNext());
}
}
I want the app to only scan when there are new files. Because If I scan the whole SD card every time then it'll take too much time for starting the app. Please Help me with that
No need to keep all the songs in local app list.
To show the mp3list you can use content provider cursor list adapter query with limit (on scroll query page by page )
To search use directly the contentprovider query method.
Only keep a playslist on you local database pointing to mp3 uri.
this link might helps you :
How to update listview whose data was queried from database through SimpleCursorAdapter?
Every time you start the app see how much space you have on your device.
File path = Environment.getDataDirectory();
megaBytesAvailable(path)
public static float megaBytesAvailable(File file) {
StatFs stat = new StatFs(file.getPath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
return bytesAvailable / (1024.f * 1024.f);
}
Save it to your app's cache as a variable and compare it every time you start the app, if it's greater then you know you need to scan.
if(comparedVariable < megaBytesAvailable(music_directory_path)){
getSongList();
//Save it again to compare next time if more storage is used
comparedVariable = megaBytesAvailable(music_directory_path);
//Save it to SharedPrefs for next boot up comparison
}
I think #royrok answer can help you, where #royrok checking the playlist in mediastore instead rescan the sdcard. Below I include #royrok answer.
Rather than rescan the card, the app iterates through all the playlists in MediaStore and checks the length of the _data field. I discovered that for all the lists with no associated M3U file, this field was always empty. Then it was just a case of finding the source code for the original android music app, finding the delete method and using that to delete any playlists with a length of 0. I've renamed the app PlaylistPurge (since it doesn't 'rescan' anymore) and am posting the code below:
package com.roryok.PlaylistPurge;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class PlaylistPurge extends ListActivity {
private List<String> list = new ArrayList<String>();
private final String [] STAR= {"*"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListAdapter adapter = createAdapter();
setListAdapter(adapter);
}
/**
* Creates and returns a list adapter for the current list activity
* #return
*/
protected ListAdapter createAdapter()
{
// return play-lists
Uri playlist_uri= MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor= managedQuery(playlist_uri, STAR, null,null,null);
cursor.moveToFirst();
for(int r= 0; r<cursor.getCount(); r++, cursor.moveToNext()){
int i = cursor.getInt(0);
int l = cursor.getString(1).length();
if(l>0){
// keep any playlists with a valid data field, and let me know
list.add("Keeping : " + cursor.getString(2) + " : id(" + i + ")");
}else{
// delete any play-lists with a data length of '0'
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, i);
getContentResolver().delete(uri, null, null);
list.add("Deleted : " + cursor.getString(2) + " : id(" + i + ")");
}
}
cursor.close();
// publish list of retained / deleted playlists
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
return adapter;
}
}
Here's a link to a post on my blog about the app http://roryok.com/blog/index.php/2010/07/23/clearing-out-deleted-playlists-in-android/
UPDATE
I've found an article about Querying And Removing Media From The Android MediaStore, I included the content below.
.
.
.
Android provides a way to register different type of media, such as audio, video, and images, for consumption by any app. This is convenient if your app is, say, a music player or an image editor. Android's MediaStore is the provider for this meta data, and includes information about the media such as title, artist, size, and location.
If your application does any sort of media content creation, such as image editing or downloading audio from an external website, then you generally want to make that content accessible from any other apps that can consume it. When you create a file you can use the MediaScannerConnection to add the file and its metadata to the MediaStore.
If you delete the file from the file system, the metadata remains in the MediaStore until Android scans the system for new media, which typically happens when the system first boots up or can be called explicitly called in such a way:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory() )));
While this method works, it is time and resource consuming, as basically the entire file system must be re-scanned. An alternative is to explicitly delete the file from the MediaStore. We're going to discuss two ways to do this. The first is to query to MediaStore for the content, based on some predicate, and delete based on the unique ID the MediaStore identifies it by. The second, and easier, way to do it is to just specify the predicate in the delete statement. In this example, I'm going to be deleting an audio file based on its file name and path, but you can easily use this to delete any type of media based on any known information (such as video duration, or image dimensions).
In querying the MediaStore, you should think of it as an SQL database. You need to form your query by specifying the table (the MediaStore's external content table), the columns you need (the content’s ID), and the where clause (how to identify the content). To perform the actual query, we’re going to use the ContentResolver's query() method.
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.MediaColumns.DATA + "='" + filePath + "'", null, null);
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
cur.close();
The first argument to query() specifies the columns we want to be returned, which in this case is only "_ID". The second argument specifies that we want to look at the media stored on the external SD card (which would be internal storage on devices with no SD card). The third argument is the predicate which specifies what content we're looking for. In this case, I'm identifying the file by its path in the file system (which is what is stored in the MediaColumns.DATA column). The fourth and fifth columns are the predicate's arguments and the ordering, respectively. I'm including my predicate's arguments in the predicate itself so that's not necessary, and if your only looking for one piece of content and your predicate is specific enough to just return one row then the ordering doesn't matter.
It is very important to make the predicate specific enough so that you're guaranteed to get the exact ID you're looking for. In my case, I know that there can be only one file at a particular location, but you could use a combination of any columns (such as title, artist, and album) to find the content. Check out the MediaColumns for all the possibilities.
Once you perform the actual query, you'll want to check to see whether the MediaStore actually contains the content you're trying to delete. If you don't handle this in some way your app will crash while trying to iterate through the cursor. Once you confirm that the query returned some data, grab the ID by moving the cursor to its first position, reading the “_ID” column, and closing the cursor. It's very important that you remember to close the cursor once you've finished using it. Your app won't crash, but you'll get memory leaks and complaints in LogCat.
Now that we have the ID that the MediaStore associated with our content, we can call ContentResolver's delete() method similar to how we called its query() method.
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id);
context.getContentResolver().delete(uri, null, null);
The delete() method takes 3 arguments: the Uri to be deleted, the predicate, and the predicate arguments. We form the Uri by appending the ID we discovered by querying the MediaStore to the Uri of the audio files on external storage. Since we know exactly which row we want to delete, we don't need to specify the predicate or the predicate's arguments.
The second method to delete the content from the MediaStore takes advantage of the fact that querying and deleting from it are performed almost identically.
context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + path + "'", null);
We can use the predicate of the delete() method to specify exactly what we want to delete, rather than having to query for it beforehand. While this method is more efficient (no extra query, no cursors to deal with), it has some pitfalls. You have no way of explicitly confirming what you're deleting. You're also not able to do advanced queries with this method, such as if you wanted to delete the most recently added content (which you could do by ordering the query based on the DATE_ADDED column). However, both ways give you a way to confirm what you've deleted since the delete() method returns the number of rows that it deleted as an integer.

album_info does not contain album_id column error

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
);

Android ContentResolver.query always returns same data

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());
}

Play a song with given Audio_id in android

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.

Categories

Resources