SoundPool doesn`t play sound after clicking several times

北慕城南 提交于 2021-02-07 23:41:24

问题


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;
}

回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/35643489/soundpool-doesnt-play-sound-after-clicking-several-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!