'android sound is starting multiple times when the condition is true

I am trying to make an app that play a sound whenever the speed of the phone is over specific number, and it worked with me but I am having a little problem which is sound is duplicated and play multiple times which sounds like echo , but I need only one sound to keep playing and stop once the value speed is below the limit.

here is my code:

 @Override
 public void onLocationChanged (Location location){

   float nCurrentSpeed;

    TextView txt = (TextView) this.findViewById(R.id.textView1);


    final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);


    boolean needToPlay = nCurrentSpeed > 20.0;

    // if need to play, play when it's already not playing
    if (needToPlay && !mp.isPlaying()) {
        mp.start();
    }


    boolean needToPause = nCurrentSpeed <= 20.0;

    // if need to pause then pause only if it's playing
    if (needToPause && mp.isPlaying()) {
        mp.pause();
    }


}


Solution 1:[1]

try this

MediaPlayer mp ;


@Override
 public void onLocationChanged (Location location){

   float nCurrentSpeed;
   if(mp==null){
     mp= MediaPlayer.create(this, R.raw.sound);
     }
    

    boolean needToPlay = nCurrentSpeed > 20.0;

    // if need to play, play when it's already not playing
    if (needToPlay && !mp.isPlaying()) {
        mp.start();
    }


    boolean needToPause = nCurrentSpeed <= 20.0;

    // if need to pause then pause only if it's playing
    if (needToPause && mp.isPlaying()) {
        mp.pause();
    }


}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajay K S