屏幕熄灭时继续播放音乐

时间:2016-08-22 13:24:40

标签: java android media-player android-mediaplayer seekbar

我希望即使屏幕熄灭也能继续音乐(即使用户锁定了他的手机),当用户按下主页按钮并再次返回应用程序时暂停,应该允许他从他暂停的地方继续...类似于用户通过文件浏览器播放音乐....

这是我的代码:

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) {

}
}

3 个答案:

答案 0 :(得分:1)

基本上为了实现目标,您不应在play3.pause声明中onPause()

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

现在,当您的应用进入onPause状态时,您的播放会暂停。 顺便一点也不要忘记花些时间来实现AudioFocus处理。

答案 1 :(得分:0)

我已经了解了有关AudioFocus的所有信息,并且正在从这些来源进行处理:

Media playback the right way (Big Android BBQ 2015)

How to properly handle audio interruptions

Managing Audio Focus

AudioManager

AudioManager.OnAudioFocusChangeListener

而且,在makeweight中,您有一些关于为您的应用清理媒体资源的信息,以免吃掉一堆内存并为其他应用发布媒体编解码器,以防他们也想使用它:

Releasing the MediaPlayer

Cleaning up MediaPlayer resources

答案 2 :(得分:0)

在您的玩家活动中,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();
        }
    }
};

onClick方法中:

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);
            }

另外,我建议您将此添加到您的播放器活动(但不在onCreate内),以便正确释放媒体资源,并在触摸停止按钮时使用它,在其他情况下应停止播放:

/**
 * 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);
    }
}