1

I am trying to set up a media player with a sound which can be played and replayed as many times desired. But I am getting this error while playing the audio the first time:

08-23 14:48:52.613: E/MediaPlayer(24194): error (1, -2147483648)
08-23 14:48:52.613: V/Preschool Basics(24194): Prepare failed.: status=0x1

My code that calls the play is:

    btnPlay = (Button) findViewById(R.id.soundButton);
    btnStop = (Button) findViewById(R.id.stopButton);

    mpSound = MediaPlayer.create(this, R.raw.a);
    mpSound.setLooping(false);
    btnPlay.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
                //mpSound.start();
                Uri uri = Uri.parse("android.resource://com.test.testing/" + R.raw.a);
                //Toast.makeText(getApplicationContext(), uri.toString(), 2000).show();
                playSong(uri.toString());
                btnPlay.setVisibility(View.GONE);
                btnStop.setVisibility(View.VISIBLE);
                btnStop.setOnClickListener(stopSound);
        }
    });

View.OnClickListener stopSound = new View.OnClickListener() {
    public void onClick(View v) {
        if (mpSound != null) {
            mpSound.stop();
            //mpSound.release();
            btnPlay.setVisibility(View.VISIBLE);
            btnStop.setVisibility(View.GONE);
        }
    }
};

The playSong() function is:

    private void playSong(String songPath) {
        try {

                mpSound.reset();
                mpSound.setDataSource(songPath);
                mpSound.prepare();
                mpSound.start();

                //Stop the song and replace button
                mpSound.setOnCompletionListener(new OnCompletionListener() {
                        public void onCompletion(MediaPlayer arg0) {
                            mpSound.stop();
                            btnPlay.setVisibility(View.VISIBLE);
                            btnStop.setVisibility(View.GONE);
                        }

                });

        } catch (IOException e) {
                Log.v(getString(R.string.app_name), e.getMessage());
        }
}

My sound is located in res/raw/a.mp3

When I press the btnPlay button I am displayed with the btnStop button but nothing is playing.

I am looking to let the user play and stop and play and so forth. How can I accomplish it?

LogCat:

08-23 15:41:20.761: E/AndroidRuntime(29438): FATAL EXCEPTION: main
08-23 15:41:20.761: E/AndroidRuntime(29438): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.test.testing/com.test.testing.AlpDisplay}: java.lang.NullPointerException
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.os.Looper.loop(Looper.java:137)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread.main(ActivityThread.java:5195)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at java.lang.reflect.Method.invokeNative(Native Method)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at java.lang.reflect.Method.invoke(Method.java:511)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at dalvik.system.NativeStart.main(Native Method)
08-23 15:41:20.761: E/AndroidRuntime(29438): Caused by: java.lang.NullPointerException
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.media.MediaPlayer.create(MediaPlayer.java:824)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at com.test.testing.MusicPlayer.<init>(MusicPlayer.java:13)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at com.test.testing.AlpDisplay.<init>(AlpDisplay.java:45)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at java.lang.Class.newInstanceImpl(Native Method)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at java.lang.Class.newInstance(Class.java:1319)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-23 15:41:20.761: E/AndroidRuntime(29438):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
08-23 15:41:20.761: E/AndroidRuntime(29438):    ... 11 more
Si8
  • 9,141
  • 22
  • 109
  • 221

1 Answers1

2

It can be done much simpler. I've tested this code, it's working:

MusicPlayer.java:

public class MusicPlayer
{
    private final int songResId = R.raw.your_song;
    private final MediaPlayer mediaPlayer;

    public MusicPlayer(Context context)
    {
        mediaPlayer = MediaPlayer.create(context, songResId);
        mediaPlayer.setLooping(true);
    }

    public void setPlaying(boolean isPlaying)
    {
        if (isPlaying)
        {
            mediaPlayer.start();
        }
        else
        {
            mediaPlayer.stop();
        }
    }

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

Usage (from your Activity):

MusicPlayer musicPlayer = new MusicPlayer(this);
musicPlayer.setPlaying(true);  // play
musicPlayer.setPlaying(false); // stop
musicPlayer.setPlaying(true);  // play from the beginning    
musicPlayer.release();         // when done using MusicPlayer

Make sure you understand release().

For the songs I recommend OGG format (with maximum compression) over MP3, since it's usually taking about 50% less space and the quality is indistinguishable. You can convert your file using for example Audacity.

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • Before I test the code, the codes which should be under my `Activity` which portion will also go inside the `stopButton`? I call `release()` during onDestroy and onBackPressed function only. And also can I pass something to MusicPlayer, in case I have different files I want to play for different button? – Si8 Aug 23 '13 at 19:22
  • In the stop button listener you just need to call `musicPlayer.setPlaying(false)` (and hide your button or whatever else you want to do). In your `onPause()` method you should call `release()`, because your `Activity` is no longer visible, so you don't want to play music and you want to free resources associated with `MediaPlayer`. – Adam Stelmaszczyk Aug 23 '13 at 19:32
  • Can i post my code online for you to look? I made the changes but now my app is FC. – Si8 Aug 23 '13 at 19:33
  • Sorry, Force Close and it said unable to instantiate activity. – Si8 Aug 23 '13 at 19:34
  • You can post [SSCCE](http://sscce.org/). But the code which I posted really should work. Paste your stack trace. – Adam Stelmaszczyk Aug 23 '13 at 19:36
  • Added the LogCat in my question – Si8 Aug 23 '13 at 19:43
  • I do not have to include MusicPlayer in AndroidManifest... Do I? – Si8 Aug 23 '13 at 19:48
  • No, you don't have. It's not an Activity, just a helper class. You have NPE in `MusicPlayer.java:13`. I think it's this line: `mediaPlayer = MediaPlayer.create(context, songResId)`. Maybe `context` is null? – Adam Stelmaszczyk Aug 23 '13 at 19:48
  • I was using `mediaPlayer = MediaPlayer.create(this, songResId)` while calling within the Activity itself. I did initiate a global variable in my Activity: `MusicPlayer musicPlayer = new MusicPlayer(this);` so context shouldn't be null. – Si8 Aug 23 '13 at 19:50
  • You have to locate precisely where do you have that null. Debug step-by-step and peek the content of variables. – Adam Stelmaszczyk Aug 23 '13 at 19:53
  • I solved it using this: http://stackoverflow.com/questions/12266502/android-mediaplayer-stop-and-play (Thanks) – Si8 Aug 23 '13 at 20:37