Question

I try to write some game where i have on screen 10-30 units at the same time.

Each unit has different sounds:

  • neutral
  • get hit
  • attack
  • dead

So totally I have 4x30 = 120 wav files.

For sure it should be some dispatcher to prevent to play several sounds at the same time.

My question is:

Do I need to add SoundPool to every Unit Object or create separate class with SoundPool singelton and manage all units by this class.

I can try to do both options but I afraid that it can cause to memory leaks and performance.

Thank you

Was it helpful?

Solution

Use the below class to represent each Sound file you have. Keep them around as needed and dispose them when you are done with them in order to avoid memory leaks.

public class AndroidSound implements Sound {
int soundId;
SoundPool soundPool;

public AndroidSound(SoundPool soundPool, int soundId) {
    this.soundId = soundId;
    this.soundPool = soundPool;
}

@Override
public void play(float volume) {
    soundPool.play(soundId, volume, volume, 0, 0, 1);
}

@Override
public void dispose() {
    soundPool.unload(soundId);
}

}

Use below classes' newSound method to get a new Sound instance that you can play and dispose whenever you want. Create your Sounds and store them in a collection and use them as you need.

public class AndroidAudio implements Audio {
AssetManager assets;
SoundPool soundPool;

public AndroidAudio(Activity activity) {
    activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    this.assets = activity.getAssets();
    this.soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
}

@Override
public Music newMusic(String filename) {
    try {
        AssetFileDescriptor assetDescriptor = assets.openFd(filename);
        return new AndroidMusic(assetDescriptor);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't load music '" + filename + "'");
    }
}

@Override
public Sound newSound(String filename) {
    try {
        AssetFileDescriptor assetDescriptor = assets.openFd(filename);
        int soundId = soundPool.load(assetDescriptor, 0);
        return new AndroidSound(soundPool, soundId);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't load sound '" + filename + "'");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top