Play sound on button click android

后端 未结 11 1259
清酒与你
清酒与你 2020-11-29 16:10

How do I get a button to play a sound from raw when click? I just created a button with id button1, but whatever code I write, all is wrong.

imp         


        
11条回答
  •  粉色の甜心
    2020-11-29 16:56

    The best way to do this is here i found after searching for one issue after other in the LogCat

    MediaPlayer mp;
    mp = MediaPlayer.create(context, R.raw.sound_one);
    mp.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mp.reset();
            mp.release();
            mp=null;
        }
    });
    mp.start();
    

    Not releasing the Media player gives you this error in LogCat:

    Android: MediaPlayer finalized without being released

    Not resetting the Media player gives you this error in LogCat:

    Android: mediaplayer went away with unhandled events

    So play safe and simple code to use media player.

    To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like

    mp = MediaPlayer.create(context, R.raw.sound_two);
    

    and play it !

    Have fun!

提交回复
热议问题