您的位置:首页 > 移动开发 > Android开发

android----使用SoundPool播放声音

2016-12-16 10:42 555 查看

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 {
//当前系统的SDK版本大于等于21(Android 5.0)时
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
//传入音频数量
builder.setMaxStreams(2);
//AudioAttributes是一个封装音频各种属性的方法
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
//设置音频流的合适的属性
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
//加载一个AudioAttributes
builder.setAudioAttributes(attrBuilder.build());
mSoundPool = builder.build();
}
//当系统的SDK版本小于21时
else {//设置最多可容纳2个音频流,音频的品质为5
mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
}

soundID.put(1, mSoundPool.load(this, R.raw.clearning, 1));

//        try{
//            Thread.sleep(1000);//如果报错误sample 1 not ready 一般都是因为资源文件没有加载完.所以要设置一个睡眠时间等待加载
//        }
//        catch (Exception e){}
}


封装

/**
* 封装
*/
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;
//当前系统的SDK版本大于等于21(Android 5.0)时
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
//传入音频数量
builder.setMaxStreams(2);
//AudioAttributes是一个封装音频各种属性的方法
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
//设置音频流的合适的属性
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
//加载一个AudioAttributes
builder.setAudioAttributes(attrBuilder.build());
mSoundPool = builder.build();
}
//当系统的SDK版本小于21时
else {//设置最多可容纳2个音频流,音频的品质为5
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: