javaandroidandroid-studiosoundpool

Soundpool is not playing any sound


Im trying to make soundpool work because I need to use it for a prodject. The problem is that it's not playing any sound. Im just trying to play a test sound to see if it works. Hope someone can see what im doing wrong here.

public class MainActivity extends AppCompatActivity {

SoundPool soundPool;
int game_over;

@Override
protected void onCreate(
        Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AudioAttributes audioAttributes = new AudioAttributes
                .Builder()
                .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();
        soundPool = new SoundPool
                .Builder()
                .setMaxStreams(4)
                .setAudioAttributes(audioAttributes)
                .build();
    }
    
    game_over = soundPool.load(this, R.raw.test, 1);
    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(game_over, 1, 1, 1, 1, 1f);
        }
    });
}

}


Solution

  • set up setOnLoadCompleteListener BEFORE load call (which should use sampleId, as game_over may be not assigned yet)

    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(sampleId, 1, 1, 1, 1, 1f);
        }
    });
    game_over = soundPool.load(this, R.raw.test, 1);
    

    afaik all load methods of SoundPool are synchronous - they are returning ID of already loaded audio file. setting OnLoadCompleteListener AFTER loading audio will cause no call for this listener, as there is nothing more to load