Search code examples
javaandroidmedia-playertouch-event

Can't get Mediaplayer to stop


I am trying to get the Android mediaplayer to stop playing a sound in this onTouch methodbut it won't. Instead it starts the sound as an addition to the last one so I can hear them overlapping. If I make it looping the loop won't stop. Even if I don't use the isPlaying part but insert and check a boolean it doesn't work. Any advice?

   public boolean onTouch(View v, MotionEvent event){

   mp = MediaPlayer.create(getBaseContext(), R.raw.tara);

   if (event.getAction() == MotionEvent.ACTION_DOWN){
       Drawable myIcon = getResources().getDrawable( R.drawable.image1);
      getWindow().setBackgroundDrawable(myIcon);
      if (mp.isPlaying()){
          mp.stop();
      }
      else {
          mp.start();
      }


   }
   else if (event.getAction() == MotionEvent.ACTION_UP){

       Drawable myIconup = getResources().getDrawable( R.drawable.image2);
          getWindow().setBackgroundDrawable(myIconup);



    }

Solution

  • You create mp = MediaPlayer.create(getBaseContext(), R.raw.tara); every time onTouch is called, so you are not using the mp instance that you used to start the playback before.

    Check if the mp is null at the beginning of onTouch, and if not null, don't create a new one, but stop the current.