Ragini
Ragini

Reputation: 775

How to stop media player if other video/audio starts playing in android

I have created an android application to play text to speech file using media player but if other audio/video starts playing then also my audio plays i.e two audios are played simultaneously.

Is there any way to stop first audio before starting another audio/video.

Is there any broadcast receiver which will get called on the start of other audio.

I have used -

mediaPlayer.play() to play audio.

and mediaPlayer.pause() to pause audio.

Any help would be appreciated.

Upvotes: 2

Views: 2974

Answers (2)

Abhishek Singh
Abhishek Singh

Reputation: 9188

You should use AudioManager service to receive notification whether you receive/lost audio focus (Managing audio focus). 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
    }
}

Upvotes: 2

SpiritCrusher
SpiritCrusher

Reputation: 21043

Media player is responsible for playing . AudioManager will provides access to volume and ringer mode control. Try following code to stop previous and play next:

if (mediaplayer != null)
        if (mediaplayer.isplaying()) {
            mediaplayer.stop();
            // start your new audio
        } else {
            // start your new audio
        }

Upvotes: 0

Related Questions