Media Player start stop start

后端 未结 9 2096
死守一世寂寞
死守一世寂寞 2020-12-10 13:09

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second

9条回答
  •  攒了一身酷
    2020-12-10 13:38

    Try this: You should use only one mediaplayer object

        public class PlayaudioActivity extends Activity {
    
        private MediaPlayer mp;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button) findViewById(R.id.button1);
        Button b2 = (Button) findViewById(R.id.button2);
        final TextView t = (TextView) findViewById(R.id.textView1);
    
        b.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
            stopPlaying();
            mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
            mp.start();
            }
    
        });
    
        b2.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
            stopPlaying();
            mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
            mp.start();
            }
        });
        }
    
        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }
    

提交回复
热议问题