42

I am trying to play a sound file on the click of a button. The sound is just 1 sec long. It plays well the first few times I click the button, but after a while it gives a NullPointerException. Here's the code:

button[i].setOnClickListener(new OnClickListener() {
    public void onClick(View view) {        
        mp = MediaPlayer.create(Test.this, R.raw.mysound);   
        mp.start();
    }
});

And here's the exception:

07-29 23:07:27.690: ERROR/AndroidRuntime(10542): Uncaught handler: thread main exiting due to uncaught exception
07-29 23:07:27.710: ERROR/AndroidRuntime(10542): java.lang.NullPointerException
07-29 23:07:27.710: ERROR/AndroidRuntime(10542):     at com.example.mypackage.Test$3.onClick(Test.java:270)
Buddy
  • 10,874
  • 5
  • 41
  • 58
Chris
  • 3,787
  • 13
  • 42
  • 49
  • 3
    not sure if it helps, but maybe try a mp.reset() on completion? – Mathias Conradt Jul 30 '10 at 06:40
  • If you want to have the resources managed automatically, so that you can call `MusicManager.getInstance().play(this, R.raw.my_sound);` etc., this library might be for you: https://github.com/delight-im/Android-Audio – caw Apr 01 '15 at 22:33

5 Answers5

101

Thanks you for your answers! Appreciate it!

Here's how I finally managed to get it work:

            button[i].setOnClickListener(new OnClickListener() {
                public void onClick(View view) {

                    mp = MediaPlayer.create(Test.this, R.raw.mysound);
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            // TODO Auto-generated method stub
                            mp.release();
                        }

                    });   
                    mp.start();
                }

            });
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
Chris
  • 3,787
  • 13
  • 42
  • 49
24

You can also try:

final soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
final sound = soundPool.load(this, R.raw.mysound, 1);

button[i].setOnClickListener(new OnClickListener()
{
     public void onClick(View view)
     {       
         soundPool.play(sound, 1.0f, 1.0f, 0, 0, 1.0f);
     }
});
Yoav Epstein
  • 849
  • 9
  • 7
  • 6
    Seems like this is the better way to do it when playing a repetitive, short sound on button click (rather than creating/destroying a media player each time). Don't forget to do a `soundPool.release();` in your `onDestroy` (or wherever you're cleaning up the Activity) though. – Alconja Aug 19 '13 at 01:43
  • @Alconja In my experience there isn't any guarantee onDestroy will actually be called (i.e. the Android task killer usually kills my app with no warning). – Michael Apr 09 '14 at 19:16
  • @Michael whenever the app is killed this way, there's usually no need to deallocate resources as your whole process gets terminated and everything it had open and allocated is closed and deallocated automatically by the system. – Grishka Dec 26 '15 at 01:54
4

It might solve your problem,

button[i].setOnClickListener(new OnClickListener() {
    public void onClick(View view) {     
        new Thread(){
            public void run(){
                mp = MediaPlayer.create(Test.this, R.raw.mysound);   
                 mp.start();
        }.start();
    }
});
Michaël
  • 3,679
  • 7
  • 39
  • 64
sohilv
  • 1,712
  • 2
  • 16
  • 21
  • Still works fine for the first few clicks, and then gives a null pointer exception, particularly when I click buttons quickly in succession. – Chris Jul 30 '10 at 06:27
  • can you try, 1) putting check before starting. i mean check if player is in playing stage then don't execute this statement mp = MediaPlayer.create(Test.this, R.raw.mysound); mp.start(); or 2) make mp as local variable – sohilv Jul 30 '10 at 06:41
1

You should catch Exception.

try this code:

     try{
         MediaPlayer mplayer = MediaPlayer.create(contextTop, R.raw.<your sound>);
         mplayer.start();
     }catch(Exception e){
         Log.d("<your TAG here>" , "error: " + e);
     }
Vlad
  • 3,465
  • 1
  • 31
  • 24
0

If still your issue not solved then try this as it help me.

    public void playSound(int resources){
        try{
            boolean mStartPlaying = true;
            MediaPlayer  mPlayer=null;
            if (mStartPlaying==true){
                mPlayer = new MediaPlayer();

                Uri uri = Uri.parse("android.resource://YOUR_PACKAGENAME/" + resources);
                mPlayer.setDataSource(getApplicationContext(),uri);
                mPlayer.prepare();
                mPlayer.start();
            } 
            else{
                mPlayer.release();
                mPlayer = null;
            }
            mStartPlaying = !mStartPlaying;
        }
        catch (IOException e){
            Log.e(LOG_TAG, "prepare() failed");
        }

//       MediaPlayer mp = MediaPlayer.create(SpyMainActivity.this, resources);
//       mp.start();

    }

Enjoy. :)

Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188