3

我正在尝试通过SoundPool.

以下测试代码使第二次播放没有声音。仅当我在 HTC Hero 设备和模拟器上无限播放声音时才会出现这种情况。我正在使用安卓 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);
...
4

1 回答 1

1

查看代码中的这一行以获得第一个声音......

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

根据这个链接,第 5 个参数定义了循环模式。0表示无循环,-1表示永远循环。你的代码说-1,所以第一个声音永远循环,所以第二个声音不会播放。尝试将第一个声音的循环模式更改为无循环,即。0。

编辑:我想我知道你的问题。当您尝试播放声音时,样本还没有准备好,因此,您需要实现onLoadCompleteListener以便在准备好时播放样本。例子。

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

现在加载这些声音后,它们将被播放。我已经对此进行了测试,并且两种声音都会播放,因为听众确保它们在播放之前就已加载。

将此代码集成到您的代码中,它应该可以解决问题。如果没有,请告诉我,我会尝试找到另一个解决方案:)

于 2013-12-30T05:58:59.987 回答