开发者

MediaPlayer with looped audio not stopping on app onPause

I've written an app which has some looped audio playing in the background (via MediaPlayer).

When the app is ended (e.g. via use hitting back button) I call开发者_如何转开发 onPause and try to close the mediaplayer:-

@Override
public void onPause(){
    super.onPause();
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }

However, it seems that by the time onPause is called the mediaplayer (mp) object is always null, even though the looped audio is still being played. So it can't be stopped.

The mediaplayer is declared at the top of the class and initiated in onCreate:-

public MediaPlayer mp;

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MediaPlayer mp = MediaPlayer.create(this, R.raw.longstream);
    mp.setVolume(0.2f, 0.2f);
    mp.setLooping(true);
    mp.start();
}

So, am I declaring the mediaplayer incorrectly? Or how do I get it to persist to be closed properly? And how come it is still playing if the object is null?

Any ideas gratefully received...


When you declare the MediaPlayer in your onCreate, it shadows the member mp, so all of the methods are performed on the object declared in onCreate, not on the class member:

MediaPlayer mp = MediaPlayer.create(this, R.raw.longstream);

Change it to

public MediaPlayer mp;

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mp = MediaPlayer.create(this, R.raw.longstream);
    mp.setVolume(0.2f, 0.2f);
    mp.setLooping(true);
    mp.start();
}


This is your code modified, it should work this way: the problem came from the fact that you declare mp as an attribute of your class, but you then instantiate it locally in your onCreate method.

public MediaPlayer mp;

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mp = MediaPlayer.create(this, R.raw.longstream);
    mp.setVolume(0.2f, 0.2f);
    mp.setLooping(true);
    mp.start();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜