Android SoundPool循环播放

SoundPool适用于同时播放多个短促的音乐,如游戏的音效,支持单次播放、多次播放和无限循环播放

源码

以下源码的注释对loop参数说得很明白,总结如下:

  • 0表示不循环
  • -1表示无限循环(注意该情况需主动调用stop()方法停止播放)
  • 大于0的值具体表示重复播放的次数,总的播放次数=loop+1(第一次播放加上重复播放的次数)

SondPool源码开头中loop的相关说明

1
2
3
4
5
* <p>Sounds can be looped by setting a non-zero loop value. A value of -1
* causes the sound to loop forever. In this case, the application must
* explicitly call the stop() function to stop the sound. Any other non-zero
* value will cause the sound to repeat the specified number of times, e.g.
* a value of 3 causes the sound to play a total of 4 times.</p>

Click and drag to move

play()方法的源码,其中包含对loop参数的说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Play a sound from a sound ID.
*
* Play the sound specified by the soundID. This is the value
* returned by the load() function. Returns a non-zero streamID
* if successful, zero if it fails. The streamID can be used to
* further control playback. Note that calling play() may cause
* another sound to stop playing if the maximum number of active
* streams is exceeded. A loop value of -1 means loop forever,
* a value of 0 means don't loop, other values indicate the
* number of repeats, e.g. a value of 1 plays the audio twice.
* The playback rate allows the application to vary the playback
* rate (pitch) of the sound. A value of 1.0 means play back at
* the original frequency. A value of 2.0 means play back twice
* as fast, and a value of 0.5 means playback at half speed.
*
* @param soundID a soundID returned by the load() function
* @param leftVolume left volume value (range = 0.0 to 1.0)
* @param rightVolume right volume value (range = 0.0 to 1.0)
* @param priority stream priority (0 = lowest priority)
* @param loop loop mode (0 = no loop, -1 = loop forever)
* @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
* @return non-zero streamID if successful, zero if failed
*/
public final int play(int soundID, float leftVolume, float rightVolume,
int priority, int loop, float rate) {
baseStart();
return _play(soundID, leftVolume, rightVolume, priority, loop, rate);
}

Click and drag to move

单次播放

1
soudPool.play(soundID, leftVolume, rightVolume, priority, 0, rate);

Click and drag to move

多次播放

1
2
3
4
5
6
// 重复播放1次,也就是总共播放2次
soudPool.play(soundID, leftVolume, rightVolume, priority, 1, rate);
// 重复播放2次,也就是总共播放3次
soudPool.play(soundID, leftVolume, rightVolume, priority, 2, rate);
// 重复播放3次,也就是总共播放4次
soudPool.play(soundID, leftVolume, rightVolume, priority, 3, rate);

Click and drag to move

循环播放

1
soudPool.play(soundID, leftVolume, rightVolume, priority, -1, rate);

Click and drag to move