SoundPool

开发中有碰到需要加载本地音频资源的功能模块,具体的可以看下述实现代码;



实现类:

public class SoundPoolUtils {
   
    private static SoundPool soundPool;




    // SoundPool对象
    public static SoundPool mSoundPlayer = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    public static SoundPoolUtils soundPlayUtils;
    // 上下文
    static Context mContext;


    /**
     * 初始化
     *
     * @param context
     */
    public static SoundPoolUtils init(Context context) {
        if (soundPlayUtils == null) {
            soundPlayUtils = new SoundPoolUtils();
        }


        // 初始化声音
        mContext = context;


        mSoundPlayer.load(mContext, R.raw.exception, 1);// 1
        mSoundPlayer.load(mContext, R.raw.left_break, 1);// 2
        mSoundPlayer.load(mContext, R.raw.left_front, 1);// 3
        mSoundPlayer.load(mContext, R.raw.right_break, 1);// 4
        mSoundPlayer.load(mContext, R.raw.right_front, 1);// 5
        mSoundPlayer.load(mContext, R.raw.exceptions, 1);// 5


        return soundPlayUtils;
    }


    /**
     * 播放声音
     *
     * @param soundID
     */
    public static void play(final int soundID) {
        mSoundPlayer.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                mSoundPlayer.play(soundID, 1, 1, 10, 0, 1);  //防止系统内存不够导致的无声问题
            }
        });


    }

}



调用方式如下:

1:初始化资源文件:

 SoundPoolUtils .init(context);



2:调用函数播放音频

SoundPoolUtils .play(1);  或者play(2)...依此类推

备注:播放视频的时候,一定是需要做个延时,或者在onClick里面实现,因为初始化资源是需要花一定时间的

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值