Android 短提示音播放SoundPool 和AndroidStudio添加raw文件夹

音频文件可以放入raw或者assets中,不同是raw一般放小型素材并且在代码中可以直接使用R.raw.xxx调用,而assets不可以。

AndroidStudio添加raw的方法:

201952495640668.jpg

 201952495858767.jpg

 点击OK,然后把音频文件拖入即可。

播放提示音代码如下:

/**
 * 播放短音频
 * */
public class SoundUtil {

    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 添加的声音资源参数
     */
    private HashMap<Integer, Integer> soundPoolMap;
    /**
     * 声音池
     */
    private SoundPool mSoundPool;
    /**
     * 单例
     */
    private static SoundUtil                 instance;

    private SoundUtil(Context context) {
        mContext = context;
    }

    public static SoundUtil getInstance(Context context) {
        if (instance == null) {
            instance = new SoundUtil(context);
            instance.init();
        }
        return instance;
    }

    /**
     * 初始化声音
     */
    public void init() {
        //sdk版本21(Android 5.0)是SoundPool 的一个分水岭
        if (Build.VERSION.SDK_INT >= 21){
            mSoundPool = new SoundPool.Builder().build();
        } else {
            /**
             * 第一个参数:int maxStreams:SoundPool对象的最大并发流数
             * 第二个参数:int streamType:AudioManager中描述的音频流类型
             * 第三个参数:int srcQuality:采样率转换器的质量。 目前没有效果。 使用0作为默认值。
             */
            mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        }

        soundPoolMap = new HashMap<>();
        //打卡成功音频文件
        putSound(1,R.raw.kq_success);
        //打卡失败音频文件
        putSound(2, R.raw.kq_fail);

    }


    private void putSound(int order, int soundRes) {
        // 上下文,声音资源id,优先级
        soundPoolMap.put(order, mSoundPool.load(mContext, soundRes, 0));
    }

    /**
     * 根据序号播放声音
     * @param order
     */
    public void playSound(int order) {
        mSoundPool.play(
                soundPoolMap.get(order),
                1f,       //左耳道音量【0~1】
                1f,       //右耳道音量【0~1】
                0,        //播放优先级【0表示最低优先级】
                0,        //循环模式【0表示循环一次,-1表示一直循环,
                          //其他表示数字+1表示当前数字对应的循环次数】
                1         //播放速度【1是正常,范围从0~2】
        );
    }

    /**
     * 释放内存
     */
    public void release() {
        if (mSoundPool != null) {
            mSoundPool.release();
            mSoundPool = null;
        }
        instance = null;
    }

}

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值