Play sound on button click android

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

    Tested and working 100%

    public class MainActivity extends ActionBarActivity {
        Context context = this;
        MediaPlayer mp;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);
            mp = MediaPlayer.create(context, R.raw.sound);
            final Button b = (Button) findViewById(R.id.Button);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    try {
                        if (mp.isPlaying()) {
                            mp.stop();
                            mp.release();
                            mp = MediaPlayer.create(context, R.raw.sound);
                        } mp.start();
                    } catch(Exception e) { e.printStackTrace(); }
                }
            });
        }
    }
    

    This was all we had to do

    if (mp.isPlaying()) {
        mp.stop();
        mp.release();
        mp = MediaPlayer.create(context, R.raw.sound);
    }
    

提交回复
热议问题