Android - play sound on button click - Null pointer exception

前端 未结 5 1594
别那么骄傲
别那么骄傲 2020-11-28 22:15

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 <

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 23:07

    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();
                    }
    
                });
    

提交回复
热议问题