Search code examples
androidmedia-playerandroid-mediaplayer

MediaPlayer.start() cannot be called in constructor?


Trying to reduce the number of lines when using MediaPlayer in numerous places throughout my application, I subclass MediaPlayer and in the constructor I call the same 3 lines that repeat each time I need to play a media file:

public MyMediaPlayer(Context context, int resid) {
    create(context, resid);
    setOnCompletionListener(this);
    start();        
}

So that instead of those 3 lines, I only place this in the caller:

new MyMediaPlayer(this, R.raw.happybirthday);

It compiles and build and even runs, but the media file won't play for some reason.

I checked the LogCat and noticed:

07-19 20:00:51.124: E/MediaPlayer(16517): start called in state 1
07-19 20:00:51.124: E/MediaPlayer(16517): error (-38, 0)

What do these errors mean?

What am I missing?

BTW, onCompletion() is called and runs fine.


Solution

  • It means this: MediaPlayer abides a state diagram and you cannot call start() in every state. Below is the state diagram and you are not calling start in Prepared, PlaybackCompleted or Paused.

    Even if you are doing it in correct state, calling it in onCreate or any of the other initialization methods directly is not a good practice because those methods are reserved for initializing your layout and application.

    You can do the following in one of onCreate() or onStart() to ensure it is played after they are completed.

    // delaying play until after all application initialization is done
        findViewById(R.id.main_page_layout).post(new Runnable() {
           public void run() {
             //play your music here
           }
        });
    

    enter image description here