10

I'm learning Android and I've created an activity that has two buttons:A ToggleButton(Play/Pause) and a Button(Next). I have two songs that would like to be cycled upon pressing Next. I have an array

int [] songs={R.raw.song1,R.raw.song2};

I overrode the onClick in my Activity. The first song plays fine; but after pressing Next, I get the following errors:

Couldn't open file on client side, trying server side

E/MediaPlayer(3107): start called in state 4

E/MediaPlayer(3107): error (-38, 0)

E/MediaPlayer(3107): Error (-38,0)

E/MediaPlayer(3107): error (1, -2147483648)

E/MediaPlayer(3107): Error (1,-2147483648)

In onCreate(Bundle...),

if(mp!=null) mp.release();
  mp=MediaPlayer.create(this, songs[count]);

Here's my onClick(View v) method:

public void onClick(View view) {    
    Log.v(TAG,"ID:"+view.getId());
    switch (view.getId()) {
    case R.id.playerbutton:  //ToggleButton
        if(state==0) {
            mp.start();
            state=1;
        }
        else if(state==1) {
            state=0;
            mp.pause();
        }   
    break;

    case R.id.next:  //Next button
        Log.v(TAG,"Next button pressed!");
        count=(count+1)%2;  //Have only two songs
        mp.reset();
        try {
            mp.setDataSource(this, Uri.parse("android.resource://com.example.myfirstapp"+songs[count]));
            mp.setOnPreparedListener(this);
            mp.prepareAsync();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mp.start();
    break;
    }
}

Basically, I'm doing this for every press of the Next button: -reset mp (i.e. the MediaPlayer object) -set a new data source for playing the next song -start mp

As for using setOnPreparedListener or prepareAsync, I read this SO question.

Where am I going wrong?

Community
  • 1
  • 1
Kedar Paranjape
  • 1,822
  • 2
  • 22
  • 33
  • possible duplicate of [Android MediaPlayer Problems :"Error (-38 , 0) " and "stop called in state 1"](http://stackoverflow.com/questions/11913108/android-mediaplayer-problems-error-38-0-and-stop-called-in-state-1) – rds Jun 22 '15 at 08:54

1 Answers1

8

I believe you are setting the datasource wrong.

Change it to:

mp.setDataSource(this, Uri.parse("android.resource://com.example.myfirstapp/"+songs[count]));

Notice the trailing slash after the package name.

Ken Wolf
  • 23,133
  • 6
  • 63
  • 84