In my app, I have a media player which play a stream music:
globalVariable.setPlaying(true);
final ProgressDialog mProgressDialog;
mProgressDialog = ProgressDialog.show(MainActivity.this, "Chargement en cours", "La musique est en train de charger", true);
String url = "http://178.32.181.86:18000";
globalVariable.mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
globalVariable.mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
globalVariable.mp.prepareAsync();
globalVariable.mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
bouton.setImageResource(R.drawable.pause);
mProgressDialog.hide();
}
});
It works very fine. When I open another app in front of mine, player continues, and it's great. But if I launch another player (like GooglePlayMusic or youtube), my app doesn't stop music and I have two sounds in the same time.
So I want that my music stop if another app need to play music.
Thanks a lot
You should use AudioManager service to receive notification whether you receive/lost audio focus (Managing audio focus). I've done similar thing in a project where when my app starts playing, Google Play pause and vice versa. Use the following code where you are controlling your media playback like (activity or service)-
// Add this code in a method
AudioManager am = null;
// Request focus for music stream and pass AudioManager.OnAudioFocusChangeListener
// implementation reference
int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
// Play
}
// Implements AudioManager.OnAudioFocusChangeListener
@Override
public void onAudioFocusChange(int focusChange)
{
if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
// Pause
}
else if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
{
// Resume
}
else if(focusChange == AudioManager.AUDIOFOCUS_LOSS)
{
// Stop or pause depending on your need
}
}
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or don't
}
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