SoundPool适合短频播放
初始化
初始化SoundPool 我们直接new SoundPool (int maxStreams, int streamType, int srcQuality)即可
参数解释:
![这里写图片描述](https://img-blog.csdn.net/20161216101352748?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvT3RsZGFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
加载音频
![这里写图片描述](https://img-blog.csdn.net/20161216101501687?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvT3RsZGFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
播放音频
![这里写图片描述](https://img-blog.csdn.net/20161216101527060?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvT3RsZGFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
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);
}
}