简体   繁体   English

Java:Android:MediaPlayer有时会在onResume上返回null

[英]Java: Android: MediaPlayer sometimes returning null onResume

I'm trying to get music to play on my app but I've hit a problem which I can't figure out. 我正在尝试让音乐可以在我的应用程序上播放,但是遇到了一个我无法解决的问题。 When I first load the program, it works fine and the music loads and plays. 当我第一次加载程序时,它可以正常工作,并且可以加载和播放音乐。 If I let the phone idle and then come back to it, the app works again. 如果我让手机处于空闲状态,然后再返回,则该应用程序将再次运行。 But the third time I let it idle and return, the mediaplayer will return a null and crash the app on resuming. 但是我第三次让它空闲并返回时,mediaplayer将返回null并在恢复时使应用程序崩溃。 Here is the code for the mediaplayer: 这是mediaplayer的代码:

    public void startMusic(Context context)
{           
    if (music != null){
        if (music.isPlaying()){
            music.stop();
        }
        music.release();
        music = null;
    }

    music = MediaPlayer.create(context, R.raw.song);

    music.setLooping(true);
    musicPlaying = true;   
}

The app will crash when it hits the music.setLooping(true); 碰到music.setLooping(true);时,应用将崩溃music.setLooping(true); line of code, saying that music is null. 代码行,说音乐为空。

Any ideas? 有任何想法吗?

It turns out I was releasing the music in the wrong place. 原来我在错误的位置放音乐。 I was doing it in the view, when I should have been doing it in the activity. 我认为应该在活动中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM