Is there any way to get the details of current song played by MediaPlayer?
问题:
回答1:
Just for reference, this works:
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
public class MediaPlayer extends Activity {
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter iF = new IntentFilter();
iF.addAction("com.android.music.metachanged");
iF.addAction("com.android.music.playstatechanged");
iF.addAction("com.android.music.playbackcomplete");
iF.addAction("com.android.music.queuechanged");
registerReceiver(mReceiver, iF);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
Log.d("mIntentReceiver.onReceive ", action + " / " + cmd);
String artist = intent.getStringExtra("artist");
String album = intent.getStringExtra("album");
String track = intent.getStringExtra("track");
Log.d("Music",artist+":"+album+":"+track);
}
};
}
回答2:
There is no documented method for getting info on the currently playing file from a MediaPlayer instance, you'll need to make your app store that information itself in another way. If you're using a Service to keep track of your MediaPlayer instance (which I'd recommend) then this shouldn't be too hard.
回答3:
I think you need to have your own model classes from wherein you can set and get your song title. For this and other information, see Stack Overflow question:
How to set the PlayList Index for Mediaplayer(ExpressionMediaPlayer:Mediaplayer).
If you are keen to know how it is being implemented, you can get the source and see how they have implemented.
回答4:
I learned how to do it just now, so I don't know if it works on all versions of android yet.
private void getTrackInfo(Uri audioFileUri) {
MediaMetadataRetriever metaRetriever= new MediaMetadataRetriever();
metaRetriever.setDataSource(getRealPathFromURI(audioFileUri));
String artist = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
String title = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
}
private String getRealPathFromURI(Uri uri) {
File myFile = new File(uri.getPath().toString());
String s = myFile.getAbsolutePath();
return s;
}