android使用SoundPool 播放短音效

 播放短音效

1,准备资源文件(短音效文件)

      在eclipse中,将准备好的声音文件放到res下的raw目录下(在res下新建一个文件名为raw的即可)

2,新建一个activity(包括两个Button),在activity中实现短音效的播放,如下:

   声明SoundPool

private SoundPool sp;       //得到一个声音池引用
private HashMap<Integer,Integer> spMap;   //得到一个map的引用

   onCreate(Bundle savedInstanceState) 中的代码:

initiSoundPool();
btn_shortmusic1 = (Button) findViewById(R.id.shortmusic1);
but_shortmusic2 = (Button) findViewById(R.id.shortmusic2);

btn_shortmusic1.setOnClickListener(this);
but_shortmusic2.setOnClickListener(this);

   initiSoundPool();

 public void initiSoundPool()
 {
  sp=new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
  spMap=new HashMap<Integer, Integer>();
  spMap.put(1, sp.load(this,R.raw.sound1,1));
  spMap.put(2, sp.load(this,R.raw.sound2,1));
 }

   palySounds():

 public void playSound(int sound,int number){ //sound:播放音效的id,number:放音效的次数
     AudioManager am=(AudioManager)this.getSystemService(this.AUDIO_SERVICE);//实例化AudioManager对象
     float audioMaxVolumn=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); //返回当前AudioManager对象的最大音量值
     float audioCurrentVolumn=am.getStreamVolume(AudioManager.STREAM_MUSIC);//返回当前AudioManager对象的音量值
     float volumnRatio=audioCurrentVolumn/audioMaxVolumn;
     sp.play(
       spMap.get(sound),      //播放的音乐id
       volumnRatio,       //左声道音量
       volumnRatio,       //右声道音量
       1,          //优先级,0为最低
       number,        //循环次数,0无不循环,-1无永远循环
       1         //回放速度 ,该值在0.5-2.0之间,1为正常速度
     );
    }

onClick(View arg0):

@Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch (arg0.getId()) {
  case R.id.shortmusic1:
   playSound(1,1);
   break;
  case R.id.shortmusic2:
   playSound(2,1);
   break;


转载于:https://my.oschina.net/u/2393951/blog/486146

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值