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

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);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值