Android 中声音的处理二:SoundPool

SoundPool主要用在播放一些短的反应速度要求高的声音上,比如:音效。
    SoundPool和其他声音播放类相比,其特点是可以自行设置声音的品质、音量、播放比率等参等。并且它可以同时管理多个音频流,每个流都有独自的ID,对某个音频流的管理都是通过ID进行的。
    基本使用步骤:
 1.创建一个SoundPool

SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
     
public SoundPool(int maxStream, int streamType, int srcQuality)
maxStream //同时播放的流的最大数量
streamType //流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)
srcQuality // 采样率转化质量,当前无效果,使用0作为默认值

  2.从资源或者文件载入音频流:

    SoundPool的加载:

load(Context context, int resId, int priority);
       
int  load(Context context, int resId, int priority)  //从APK资源载入
int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor对象载入 
int  load(AssetFileDescriptor afd, int priority)  //从Asset对象载入
int  load(String path, int priority)  //从完整文件路径名载入
priority //优先级
     一般把多个声音放到HashMap中去,同时把资源放到一个数组中比如:
int rid[] = {R.raw.res0,R.raw.res1,R.raw.res2,R.raw.res3,};
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
soundPoolMap = new HashMap<Integer, Integer>();
int i = 0;
for(i;i<rid.lenght;i++)
{
    soundPoolMap.put(i+1, soundPool.load(this, res[i], 1));
}

  3.SoundPool的播放控制:

    play:

AudioManager audioManager = (AudioManager)mContext.
    getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = audioManager.
    getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax= audioManager.
    getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//得到音量的大小
float volume = streamVolumeCurrent/streamVolumeMax;    
//播放声音
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);
     
play (int soundID, float leftVolume, float rightVolume,
        int priority, int loop, float rate);
leftVolume //左音量
rightVolume //右音量,
priority //优先级,
loop //循环次数,
rate //表示速率,如:速率最低0.5最高为2,1代表正常速度
SoundPool的常用方法包括:
    load()        //加载音频文件
    pause()       //暂停
    play()        //播放
    resume()      //恢复
    setLoop()     //设置循环模式
    setOnLoadCompleteListener()    //设置监听器
    setVolume()   //设置音量
    setRate()     //设置播放速率

SoundPool最大分配了1M的空间。其中stop(),pause()还存在bug,避免使用。

使用心得:在用到这个函数时发现,如果你的load很多次(我的测试是在475次左右时)就会load失败。我不知道是不是因为load过程有创建内存,而之后没有释放。
我解决办法是在Play后,调用unload方法,就不会出现load失败。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值