nAkhmedov
nAkhmedov

Reputation: 3592

SoundPool doesn`t play sound after clicking several times

When i click button plays sound on my app, but keep clicking for a while doesn`t play anymore. Maybe it is memory issue? Could you solve me my issue? Here is implemented play sound via SoundPool: when i click button i called play method: and play method works background thread

private void play(int resId) {  
    soundPool = buildBeforeAPI21();//TODO: refactor with deprecated constructor
    soundPool.load(activity, Integer.parseInt(resId), 1);
}

public SoundPool buildBeforeAPI21() {
    if (soundPool == null) {
        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                if (status == 0) {
                    soundPool.play(sampleId, 1.0f, 1.0f, 1, 0, 1.0f);
                }
            }
        });
    }
    return soundPool;
}

Upvotes: 3

Views: 2533

Answers (2)

Xose Sanchez
Xose Sanchez

Reputation: 318

Maybe this answer cames too late; but here we go. The problem is in the line

    soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);

That '2' number is the int maxStreams, following the documentation "the maximum number of simultaneous streams for this SoundPool object" (you can go deep on this here). Now change it and set it to 10, for example, and try again. And after that, you cand adjust it as your wishes. So:

        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

Hope this helps (if it is still necessary).

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317372

Don't create a new SoundPool with each click. That is extremely wasteful. Do this instead:

1) Create the SoundPool just once 2) Load it with all the sounds you want to play, just once 3) Wait for all the sounds to load 4) Just call soundPool.play() with each click.

Upvotes: 1

Related Questions