MediaPlayer function search for specific song - android

I want to make an mp3 app in which the user gives a text and then it plays that song. So far, I have this function in mind:
public void searchSong(String x) {
mp = MediaPlayer.create(MainActivity.this, R.raw.x);
mp.start();
}
where x is the name stored, But ofcourse this gives an error saying "x cannot be resolved or is not a field". How can I fix that? Thanks a lot

If your songs have already stored in a specific location of sdcard,you can get the uri of song file ,then use mp.setDataSource() to bind what will be played.
If you want to search songs by specific song name, you can use android.provider.MediaStore.The Media provider contains meta data for all available media on both internal and external storage devices include song name.
A simple query code snippet is like this:
public void searchSong(String songName) {
final String[] projections = new String[] {
android.provider.MediaStore.Audio.Media.ARTIST,
android.provider.MediaStore.Audio.Media.DATA };
final String selection = Media.TITLE + " = ?";
final String[] selectionArgs = new String[] { songName };
Cursor cursor = mContentResolver
.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projections, selection, selectionArgs,
Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
int indexFilePath = cursor.getColumnIndex(Media.DATA);
int indexArtist = cursor.getColumnIndex(Media.ARTIST);
while (cursor.moveToNext()) {
// Get the informations of the song
cursor.getString(indexArtist);
cursor.getString(indexFilePath);
// Then do what you want
}
cursor.close();
}
}

Related

Playing MediaStore.Audio.Media Entries

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));
// ....
}

Adding tracks to playlist

I'm working on playlist in my audio player. I have return a code to add songs to playlist. The code works fine, but i have a small problem though. The problem is if I add a single song to playlist, two copies of the same song are added. It is like, if I add song A to playlist and then I open the playlist to which I added song A, I can see two copies of song A in there.
Code:
public static void AddSongToPlaylist(long songID, long pID, Context context ){
Uri pUri = MediaStore.Audio.Playlists.Members.getContentUri("external", pID);
ContentResolver resolver = context.getContentResolver();
ContentValues values = new ContentValues();
String[] cols = new String[] {
"count(*)"
};
Cursor cur = resolver.query(pUri, cols, null, null, null);
cur.moveToFirst();
final int base = cur.getInt(0)+1;
cur.close();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER,base);
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songID);
resolver.insert(pUri,values);
resolver.notifyChange(Uri.parse("content://media"), null);
Log.i("URI:",resolver.insert(pUri, values)+"");
Toast.makeText(context, "Song Added", Toast.LENGTH_SHORT).show();
Log.i("Song ID:", String.valueOf(songID));
}
Stop calling resolver.insert() again through Log.i().

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 .

How to get the duration of video from MediaStore?

I used this answer to get the duration,but it's not working for me.Can anybody tell me what's the problem?
Any help is appreciated.
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] columns = {MediaStore.Video.VideoColumns.DURATION};
String selection = MediaStore.Video.VideoColumns.DATA + "=?";
String selectionArgs[] = {"/data/data/com.test.test/files/video1.mp4"};
Cursor cursor = context.getContentResolver().query(uri, columns, selection, selectionArgs, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
}
cursor.close();
}
If you've already got the Uri or the file path to the video, it might be easier to use the MediaMetadataRetriever class. It would look something like this:
MediaMetadataRetriever r = new MediaMetadataRetriever();
r.setDataSource(filePath);
String durString = r.extractMetadata( MediaMetadataRetriever.METADATA_KEY_DURATION );
int duration = Integer.parseInt(durString);
The MediaStore is a Media provider that contains meta data for all available media on both internal and external storage devices.I am not sure,but the path you are using maybe is not visible for MediaStore.If you are using MediaPlayer do like this...
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(uriOfYourFile));
int duration = mp.getDuration();

How to Create a Playlist

I am trying to create an app which simply offers an edittext and imagebutton. If the butten gets clicked, the idea is that an album is added to the Playlist, named in the edittext box. Albums should be selected randomly. Goes without saying that the album tracks should be in the correct order.
I can add more functionality later eg. save, overwrite, delete etc.
I have the interface but am struggling with the code. I sort of get the concept of ContentProviders.
so the code needs to:
access the Playlists, which I believe is achieved by using MediaStore.Audio.Playlists
access the Albums, which I believe is achieved by using MediaStore.Audio.Albums
add to the Playlist
I have the following code (most bits obtained from this site. Thanks btw) to access the Playlist but it crashes with a Null Exception error.
public void checkforplaylists()
{
//Get a cursor over all playlists.
final ContentResolver resolver= MediaProvider.mContentResolver;
final Uri uri=MediaStore.Audio.Playlists.INTERNAL_CONTENT_URI;
final String id=MediaStore.Audio.Playlists._ID;
final String name=MediaStore.Audio.Playlists.NAME;
final String[]columns={id,name};
final Cursor playlists= resolver.query(uri, columns, null, null, null);
if(playlists==null)
{
Log.e(TAG,"Found no playlists.");
return;
}
return;
}
Anyone who can help?
I think you mean NullPointerException, which means one of your assignments is null and then you try to access a member of the object you intended it to be. Most likely it is resolver, but to be sure you need the line number reported and/or to step through that with a debugger.
This works. When using the ContentResolver, the Context (this) is required.
public void checkforplaylists(Context context)
{
ContentResolver cr = context.getContentResolver();
final Uri uri=MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
final String id=MediaStore.Audio.Playlists._ID;
final String name=MediaStore.Audio.Playlists.NAME;
final String[]columns={id,name};
final Cursor playlists= cr.query(uri, columns, null, null, null);
if(playlists==null)
{
Log.e(TAG,"Found no playlists.");
return;
}
Log.e(TAG,"Found playlists.");
return;
}
use this code, will work
public boolean addPlaylist(String pname) {
Uri playlists = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor c = resolver.query(playlists, new String[] { "*" }, null, null,
null);
long playlistId = 0;
c.moveToFirst();
do {
String plname = c.getString(c
.getColumnIndex(MediaStore.Audio.Playlists.NAME));
if (plname.equalsIgnoreCase(pname)) {
playlistId = c.getLong(c
.getColumnIndex(MediaStore.Audio.Playlists._ID));
break;
}
} while (c.moveToNext());
c.close();
if (playlistId != 0) {
Uri deleteUri = ContentUris.withAppendedId(playlists, playlistId);
Log.d(TAG, "REMOVING Existing Playlist: " + playlistId);
// delete the playlist
resolver.delete(deleteUri, null, null);
}
Log.d(TAG, "CREATING PLAYLIST: " + pname);
ContentValues v1 = new ContentValues();
v1.put(MediaStore.Audio.Playlists.NAME, pname);
v1.put(MediaStore.Audio.Playlists.DATE_MODIFIED,
System.currentTimeMillis());
Uri newpl = resolver.insert(playlists, v1);
Log.d(TAG, "Added PlayLIst: " + newpl);
flag=true;
return flag;
}

Categories

Resources