Azurai Azurai - 5 months ago 677
Java Question

Android MediaPlayer Error( start called in state 1; error (-38, 0); Error (-38,0))

I have created a package for SoundManagement, with a single class extending MediaPlayer. I was hoping to globally control this variable. Here is my Code:

package soundmanagement;

import android.content.Context;

import android.media.MediaPlayer;

import java.io.IOException;

public class MusicManager extends MediaPlayer {

public static MediaPlayer mediaPlayer = new MediaPlayer();

public void MusicManager() {
}

public static MediaPlayer create(Context context, int musicID) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
mediaPlayer.create(context, musicID);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return mediaPlayer.create(context, musicID);
}

public void prepare() {
try {
mediaPlayer.prepare();
super.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}

public void start() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
super.start();
}

public void pause() {
mediaPlayer.pause();
super.pause();
}

public void stop() {
super.stop();
mediaPlayer.release();
}

public void release() {
mediaPlayer.release();
super.release();
}

public boolean isPlaying(boolean isPlaying) {
super.isPlaying();
return isPlaying;
}

public void setLooping(boolean setLoop) {
mediaPlayer.setLooping(setLoop);
super.setLooping(setLoop);
}
}


And in my MainActivity.class, in onCreate(), all I do is write this code in the
onCreate()
:

MusicManager.mediaPlayer.create(MainActivity.this, R.raw.riseofcc);
MusicManager.mediaPlayer.start();


The application compiles and runs fine, just no music playing once it starts up.

Answer

You're taking a curious approach to the MediaPlayer, but one thing that jumps out at me is this:

public static MediaPlayer create(Context context, int musicID) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer.create(context, musicID);
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaPlayer.create(context, musicID);
    }

You call mediaPlayer.create(), then .prepare(), then create(...) again?

Also, create is a static method, so it should be called as MediaPlayer.create and you should hold the reference to it. When you're calling prepare(), you're calling prepare() on a MediaPlayer object that hasn't been created.

Edit: If you want to keep this method, revise it accordingly:

public static MediaPlayer create(Context context, int musicID) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer = MediaPlayer.create(context, musicID);
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaPlayer;
    }
Comments