Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop MediaPlayer when an other app play music

Tags:

android

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

like image 890
Tartempion34 Avatar asked Jun 29 '14 09:06

Tartempion34


2 Answers

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
    }
}
like image 94
MARK002-MAB Avatar answered Sep 18 '22 12:09

MARK002-MAB


AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or don't
 }
like image 40
Bilel Boulifa Avatar answered Sep 20 '22 12:09

Bilel Boulifa