Play sound on button click android

后端 未结 11 1263
清酒与你
清酒与你 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:47

    • The audio must be placed in the raw folder, if it doesn't exists, create one.
    • The raw folder must be inside the res folder
    • The name mustn't have any - or special characters in it.

    On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

    Example:

    private Button myButton;
    private MediaPlayer mp;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.myactivity);
            mp = MediaPlayer.create(this, R.raw.gunshot);
    
            myButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mp.start();
                }
            });
    }
    }
    

提交回复
热议问题