In my Android application, I am playing different mp3 files using the MediaPlayer class.
The user is playing his/her own music with the default music application.
I want to:
I want to pause and resume the music of the default music player from my application.
Is it possible to do this?
To control currently playing music use this code.
AudioManager mAudioManager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
if(mode == Config.MUSIC_NEXT) {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT);
mAudioManager.dispatchMediaKeyEvent(event);
}else if(mode == Config.MUSIC_PLAY){
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY);
mAudioManager.dispatchMediaKeyEvent(event);
}
else if(mode == Config.MUSIC_PREV){
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event);
}
infact this is the only code that is working for all music apps i used. checked with
guys,try follow code,it worked for me:
// stop music player
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
//resume music player
am.abandonAudioFocus(null);
The following code will pause a default MediaPlayer by sending a broadcast:
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive()) {
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
YourApplicationClass.this.sendBroadcast(i);
}
// pause
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
sendBroadcast(i);
// play
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "play");
sendBroadcast(i);
// next
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "next");
sendBroadcast(i);
// previous
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "previous");
sendBroadcast(i);
Some more info about available commands:
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 CMDPLAY = "play";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With