Search code examples
androidaudiosoundpool

SoundManager, how to stop sound playing


I use simple SoundManager for play sounds from sounpool. My problem is, sound not stop playing when I exit from app, even I use mySound.release();. Otherwise, everything works as it should, here is my code.

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundManager {

private Context pContext;
private SoundPool mySound;

private float rate = 1.0f;
private float masterVolume = 1.0f;
private float leftVolume = 1.0f;
private float rightVolume = 1.0f;
private float balance = 0.5f;

// Constructor, setup the audio manager and store the app context
public SoundManager(Context appContext)
{
    mySound = new SoundPool(16, AudioManager.STREAM_MUSIC, 100);

  pContext = appContext;
}

// Load up a sound and return the id
public int load(int sound_id)
{
    return mySound.load(pContext, sound_id, 1);

}


// Play a sound
public void play(int sound_id)
{
    mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);    
}   

// Set volume values based on existing balance value
public void setVolume(float vol)
{
    masterVolume = vol;

    if(balance < 1.0f)
    {
        leftVolume = masterVolume;
        rightVolume = masterVolume * balance;
    }
    else
    {
        rightVolume = masterVolume;
        leftVolume = masterVolume * ( 2.0f - balance );
    }

}


public void unloadAll()
{
    mySound.release();      
}

}

Solution

  • The method play() return a int StreamId. You need to keep this StreamId on a variable and to call the stop method. For example:

    Declare a Stream Id variable:

    private int mStreamId;
    

    Then, keep it when you start a new sound stream:

    // Play a sound
    public void play(int sound_id)
    {
        mStreamId = mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);    
    }   
    

    So you can stop it doing:

    mySound.stop(mStreamId);
    

    Now you can stop your sound stream on the activities events onStop, onPause or where you want.

    EDIT:

    The best way to release your SoundPool resource is call release and set the reference to null after you stop playing the sound. For example:

    @Override
    protected void onPause() {
        super.onPause();
        mSoundManager.unloadAll();
    }
    

    On your SoundManager, change your unloadAll method to:

    public void unloadAll()
    {
        mySound.release();
        mySound = null;    
    }
    

    Note the following:

    onPause – is always called when the activity is about to go into the background.

    release: releases all the resources used by the SoundPool

    object null: this SoundPool object can no longer be used (like @DanXPrado said) so set it to null to help the Garbage Collector identify it as reclaimable.

    For more details, see this tutorial about SoundPool.

    Hope this helps.