SoundPool适合短频播放
初始化
初始化SoundPool 我们直接new SoundPool (int maxStreams, int streamType, int srcQuality)即可
参数解释:
加载音频
播放音频
SoundPool API大于21之后使用SoundPool.Builder
private SoundPool mSoundPool;
private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
private void initSP() throws Exception {
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(2);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
builder.setAudioAttributes(attrBuilder.build());
mSoundPool = builder.build();
}
else {
mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
}
soundID.put(1, mSoundPool.load(this, R.raw.clearning, 1));
}
封装
/**
* 封装
*/
public class SoundPlayUtils {
public static SoundPool mSoundPool;
public static SoundPlayUtils soundPlayUtils;
public static Context mCotext;
public static SoundPlayUtils init(Context context){
if (soundPlayUtils==null){
soundPlayUtils=new SoundPlayUtils();
}
mCotext=context;
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(2);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
builder.setAudioAttributes(attrBuilder.build());
mSoundPool = builder.build();
}
else {
mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
}
mSoundPool.load(context, R.raw.clearning, 1);
return soundPlayUtils;
}
public static void play(int pid){
mSoundPool.play(pid, 1, 1, 0, 0, 1);
}
}