简体   繁体   中英

Android: Playing sound infinitely in SoundPool doesn't play for the second time after stop

I am trying to play 2 sounds via the SoundPool .

The following testing code rendered the second play with no sound. This occures only when I play the sound as infinite, both on my HTC Hero device and the emulator. I am using android 1.6.

...
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
int soundId1 = soundPool.load(getApplicationContext(), R.raw.sound1, 1);
int soundId2 = soundPool.load(getApplicationContext(), R.raw.sound2, 1);

// the first one plays
int streamId = soundPool.play(soundId1, 1.0f, 1.0f, 1, -1, 1.0f);
try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
soundPool.stop(streamId);

// the second one doesn't play
streamId = soundPool.play(soundId2, 1.0f, 1.0f, 1, -1, 1.0f);
try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
soundPool.stop(streamId);
...

Looking at this line in your code for the first sound...

int streamId = soundPool.play(sound1, 1.0f, 1.0f, 1, -1, 1.0f);

According to this link , the 5th parameter defines the loop mode. 0 for no loop or -1 for loop forever. Your code says -1 , so the first sound is looping forever so the second sound wont play. Try changing the loop mode of the first sound to no loop, ie. 0.

EDIT: I think I know your problem. The samples aren't ready when you try to play the sound, therefore, you need to implement an onLoadCompleteListener so the samples are played when they are ready. Example.

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

        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                            int arg2) {
                streamId = soundPool.play(sampleId, 1.0f, 1.0f, 1, -1, 1.0f);
               }

        });
    int soundId1 = soundPool.load(getApplicationContext(), R.raw.tick, 1);      
    int soundId2 = soundPool.load(getApplicationContext(), R.raw.tock, 1);

Now after these sounds are loaded, they will be played. I have tested this and both sounds play because the listener ensures they are loaded before they are played.

Integrate this code into yours and it should solve the problem. If it doesn't, let me know and I'll try to find another solution :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM