Search code examples
javaandroidsoundpool

cleaning up after soundPool (loop sound still plays after app is killed)


how do I clean up after soundPool? my looping sounds still play after app is killed

// my onStop() onPause() is identical the sound continues until reboot.

public void onStop(){
    soundPool.stop(curs);   
    }

  public int playSound(int sound, int loop) {
   if (curs != sound)
   {

       curs = sound;   
       AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
       float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
       float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
       float volume = streamVolumeCurrent / streamVolumeMax;  
       return soundPool.play(soundsMap.get(sound), volume, volume, 1, loop, 1);

       }
       return curs;
 }     
 // is how I call it in a runnable class

   curs=playSound(cur,-1);

Solution

  • You are never stopping your old sound when you call playSound. If playSound is called more than once, you will have two sounds playing, and when you exit, you will only cancel one of them. One solution is to hold onto all sound IDs you start. Or, if you only need one sound at a time, change your code to cancel the current sound before you start the next sound.

    if (curs != sound)
    {
      soundPool.stop(curs); 
      curs = sound;   
      // ... 
    }