0

I'm doing an alarm System. The alarms are working OK, but the sound doesn't work.. I'm doing a little test and I don't understand where is the problem.. In the Alarm activity, I've the following code:

        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
    try {
        AssetManager assetManager = getAssets();
        AssetFileDescriptor descriptor = assetManager.openFd("sound.ogg");
        mySoundId = soundPool.load(descriptor, 1);
    } catch (IOException e) {
        Log.d(TAG,"We've problem's!!, "
                + e.getMessage());
    }   

    soundPool.play(mySoundId, 1, 1, 0, 0, 1);

There are not errors.. but music doesn't work.. Instead, if I program the PLAY in a bottom work's!! Can anyone help me please??

Héctor Ortiz
  • 257
  • 1
  • 6
  • 17

1 Answers1

1

I just tried your code and found the problem. It is a common problem in SoundPool. You need to wait for the sound to finish loading before you play it. That's why soundPool.play() returned zero. The sound was not ready.

In API 8, setOnLoadCompleteListener() was introduces which will solve the problem:

soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
       //play the sound.
    }
});

however, if you are targeting lower APIs, You can't tell for sure if your sound is ready to be played or not. In this case, I suggest you use MediaPlayer.

iTurki
  • 16,292
  • 20
  • 87
  • 132