以前播放音频都是使用MediaPlayer来播放,但MediaPlayer的创建和销毁都是非常销毁资源的,如果要播放一些短的音频,使用MediaPlayer就不太合适了。这个时候我们就需要用到SoundPool;
public class SoundPool extends Object
a.初始化SoundPool
SoundPool soundPool = new SoundPool(maxStreams, streamType, srcQuality);
参数:
参数 | 解释 |
---|---|
maxStreams | 最大的流的数量 |
streamType | 流的类型(一般AudioManager.STREAM_SYSTEM) |
srcQuality | 频的质量,默认是0,目前没有影响 |
streamType :
1. STREAM_ALARM
2. STREAM_DTMF
3. STREAM_MUSIC
4. STREAM_NOTIFICATION
5. STREAM_RING
6. STREAM_SYSTEM
7. STREAM_VOICE_CALL
b.加载音频
返回值 | 方法 | 解释 |
---|---|---|
int | load (AssetFileDescriptor afd, int priority) | Load the sound from an asset file descriptor |
int | load (String path, int priority) | Load the sound from the specified path |
int | load (Context context, int resId, int priority) | Load the sound from the specified APK resource |
int | load (FileDescriptor fd, long offset, long length, int priority) | Load the sound from a FileDescriptor |
一般使用load(Context context, int resId, int priority)
方法加载音频:
context : 上下文;
resId :音频文件地址(R.raw.xxx);
priority : 声音优先级,默认1即可。
c.音频播放
int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
soundId : 音频的ID,load()的返回值;
leftVolume : 左声道值(范围= 0.0到1.0);
rightVolue : 右声道值(范围= 0.0到1.0);
priority : 流优先级(0 是最低优先级);
loop : 循环播放次数,0为不循环,-1为永远循环;
rate : 播放速率(1.0 是正常播放,范围0.5至2.0).
d.代码总结
//初始化
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
//加载音频文件
soundId = soundPool.load(context, R.raw.xxx, 1);
//播放音频文件
int res = soundPool.play(soundId, 0.3f, 0.3f, 1, -1, 1);
//停止播放音频
soundPool.stop(res);
e.资源释放
@Override
protected void onDestroy(){
super.onDestroy();
if(soundPool != null){
soundPool.release();
}
}