Devk
Devk

Reputation: 117

continue playing the music when screen goes off

I want to continue the music even if the screen goes off(even if user locks his phone), pause when the user presses the home button and returning to the app again should allow him to continue from where he paused...similar to the user playing music via a file browser....

Here's my code:

public class prathmeshvara extends AppCompatActivity implements Runnable,  View.OnClickListener, SeekBar.OnSeekBarChangeListener{
TextView tv25;
Button b47, b48, but32;
int count = 0;
MediaPlayer play3;
SeekBar seek_bar3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_prathmeshvara);
    ActionBar actionBar=getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.mipmap.icon);
    tv25 = (TextView) findViewById(R.id.textView25);
    tv25.setText(Html.fromHtml(getString(R.string.twentyone)));
    b47 = (Button) findViewById(R.id.b47);
    b48 = (Button) findViewById(R.id.b48);
    seek_bar3 = (SeekBar) findViewById(R.id.seekBar3);
    seek_bar3.setOnSeekBarChangeListener(this);
    seek_bar3.setEnabled(false);
    but32 = (Button) findViewById(R.id.button32);
    but32.setOnClickListener(this);
}

public void run() {
    int currentPosition = play3.getCurrentPosition();
    final int total = play3.getDuration();
    while (play3 != null && currentPosition < total) {
        try {
            Thread.sleep(1000);
            currentPosition = play3.getCurrentPosition();
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            return;
        }
        seek_bar3.setProgress(currentPosition);
    }
}

public void onClick(View v) {
    if (v.equals(but32)) {
        if (play3 == null) {
            play3 = MediaPlayer.create(getApplicationContext(), R.raw.prathameshwara);
            seek_bar3.setEnabled(true);
        }
        if (play3.isPlaying()) {
            play3.pause();
            but32.setBackgroundResource(R.drawable.play);
        } else {
            play3.start();
            but32.setBackgroundResource(R.drawable.pause);
            seek_bar3.setMax(play3.getDuration());
            new Thread(this).start();
        }
    }
    play3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            play3.seekTo(0);
            but32.setBackgroundResource(R.drawable.play);
        }
    });
}

@Override
protected void onPause()
{
    super.onPause();
    if (play3!= null)
    {
        play3.pause();
    }
}

@Override
protected void onResume()
{
    super.onResume();
    if ((play3 != null) && (!play3.isPlaying())) {
        but32.setBackgroundResource(R.drawable.play);
        but32.setOnClickListener(this);
    }
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    try {
        if (play3.isPlaying() || play3 != null) {
            if (fromUser)
                play3.seekTo(progress);
        } else if (play3 == null) {
            Toast.makeText(getApplicationContext(), "First Play", Toast.LENGTH_SHORT).show();
            seek_bar3.setProgress(0);
        }
    } catch (Exception e) {
        Log.e("seek bar", "" + e);
        seek_bar3.setEnabled(false);
    }
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
}

Upvotes: 1

Views: 1397

Answers (3)

Denis Pisarev
Denis Pisarev

Reputation: 584

In your player activity, before onCreate:

import android.media.AudioManager;

...

/** Handles audio focus when playing a sound file */
private AudioManager mAudioManager;

/**
 * This listener gets triggered when the {@link MediaPlayer} has completed
 * playing the audio file.
 */


/**
 * This listener gets triggered whenever the audio focus changes
 * (i.e., we gain or lose audio focus because of another app or device).
 */
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener(){
    @Override
    public void onAudioFocusChange(int focusChange){
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
                // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
                // our app is allowed to continue playing sound but at a lower volume. We'll treat
                // both cases the same way because our app is playing short sound files.

                // Pause playback and reset player to the start of the file. That way, we can
                // play the word from the beginning when we resume playback.
                mMediaPlayer.pause();
                mMediaPlayer.seekTo(0);
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
                mMediaPlayer.start();
        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                // The AUDIOFOCUS_LOSS case means we've lost audio focus and
                // Stop playback and clean up resources
                releaseMediaPlayer();
        }
    }
};

inside the onClick method:

int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                    AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
                // we have audio focus now

                // Create and setup the {@link MediaPlayer} for the audio resource associated with the current word
                mMediaPlayer = MediaPlayer.create(YourActivity.this, word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }

Also I suggest you to add this to your player activity (but not inside onCreate) in order to release media resources properly, and use it when Stop button touched and in other cases when the playback should be stopped:

/**
 * Clean up the media player by releasing its resources.
 */
private void releaseMediaPlayer() {
    // If the media player is not null, then it may be currently playing a sound.
    if (mMediaPlayer != null) {
        // Regardless of the current state of the media player, release its resources
        // because we no longer need it.
        mMediaPlayer.release();

        // Set the media player back to null. For our code, we've decided that
        // setting the media player to null is an easy way to tell that the media player
        // is not configured to play an audio file at the moment.
        mMediaPlayer = null;

        // Regardless of whether or not we were granted audio focus, abandon it. This also
        // unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
        mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
    }
}

Upvotes: 0

Denis Pisarev
Denis Pisarev

Reputation: 584

I've learned all about AudioFocus and it's handling from these sources:

Media playback the right way (Big Android BBQ 2015)

How to properly handle audio interruptions

Managing Audio Focus

AudioManager

AudioManager.OnAudioFocusChangeListener

And, in a makeweight, here you have some info about cleaning up media resourses for your app to not to eat a bunch of memory and release media codec for other apps in case they want to use it too:

Releasing the MediaPlayer

Cleaning up MediaPlayer resources

Upvotes: 0

Denis Pisarev
Denis Pisarev

Reputation: 584

Basically to reach your goal you should not do play3.pause in onPause() statement:

@Override
protected void onPause()
{
    super.onPause();
    if (play3!= null)
    {
        play3.pause();
    }
}

Right now when your app comes into onPause state, your playback pauses. Btw don't forget to spend some time and implement AudioFocus handling.

Upvotes: 1

Related Questions