Search code examples
androidmedia-playersoundpool

How to Play two Different sound on two different buttons?


I have 2 sound clips 19 sec each on the click of button1 Soundclip1 should play and on the click of button2 the playing Soundclip1 should stop and Soundclip2 should start.. Please help me i am stuck. i research about this a lot but my problem is both of the sound playing simultaneously....

Please.... I have refered this Android Media Player Wont Play After Stop and Stop the prevoius sound before starting a new sound in my android app


Solution

  • Try this-

    final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.one);
    final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
    
    Button btn = (Button)this.findViewById (R.id.button1);
    btn.setOnClickListener(new OnClickListener(){
        @override
        public void onClick(View v) {
            mp1.start();
            mp2.pause();
            mp2.seekTo(0);
        }
    });
    
    Button btn1 = (Button)this.findViewById (R.id.button2);
    btn1.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            mp1.pause();
            mp1.seekTo(0);
            mp2.start();
        }
    });