2
votes

I want to have two different background music loops playing depending on the state of the app. To do so I tried that code:

private void backgroundMusicPlayer() {
    if (gameMode == 0) {
        if (backgroundloop2 != null) {
            backgroundloop2.pause();
            backgroundloop2.stop();
            backgroundloop2.release();
            backgroundloop2 = null;
        }
        backgroundloop1 = MediaPlayer.create(getContext(), R.raw.gameloop1);
        backgroundloop1.setLooping(true);
        backgroundloop1.start();
    }
    else {
        if (backgroundloop1 != null) {
            backgroundloop1.pause();
            backgroundloop1.stop();
            backgroundloop1.release();
            backgroundloop1 = null;
        }
        backgroundloop2 = MediaPlayer.create(getContext(), R.raw.gameloop2);
        backgroundloop2.setLooping(true);
        backgroundloop2.start();
    }
}

But I just get errors:

"MediaPlayer: start called in state 64" "MediaPlayer: pause called in state 8" "Failed to open libwvm.so: dlopen failed: library "libwvm.so" not found" "Media Player called in state 0, error (-38,0)"

How can I do it properly?

1
I don't know, arent u code missing a "player.prepare()" ? - Marcos Vasconcelos
Actually not. the create() method automatically calls the prepare() method. - MilamberMilamber

1 Answers

0
votes

Why IllegalStateException in onPause()?

In Android Documentation for onPause:

IllegalStateException
If the internal player engine has not been initialized.

In the document, you can see a maximum of media player methods would throw you IllegalStateException for some reason.

So use try catch for all of your media player operations.

Android recommends looking for Exceptions while using media player object.

It is good programming practice to always look out for IllegalArgumentException and IOException that may be thrown from the overloaded setDataSource methods.