关于Android音效播放,【备忘】

主要还是希望开箱即用。所以才有了这篇,也是备忘。

以下代码适合Android5.0版本以后

        private SoundPool soundPool;//特效播放
    	private Map<String,Integer> soundPoolMap;//       
        Builder builder=new SoundPool.Builder();
        builder.setMaxStreams(4);///最大4个声音流,播放超出时会根据优先级挤掉其他声音流。
        AudioAttributes.Builder audiobuilder=new AudioAttributes.Builder();
        //设置属性,唯一注意就是不能设置为null,不设置也可以,将使用默认设置。
        audiobuilder.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION);
        audiobuilder.setUsage(AudioAttributes.USAGE_MEDIA);
        AudioAttributes attributes=  audiobuilder.build();
        builder.setAudioAttributes(attributes);
        soundPool = builder.build();
        
        //存放载入好的声音资源ID
		soundPoolMap = new HashMap<String,Integer>();   
//	    soundPoolMap = new SparseIntArray();   
	    
	    final String bgm="bgm";
	    final String sound1="sound1";
	    soundPoolMap.put(bgm, soundPool.load(this, R.raw.sound1, 1));
	    Log.i(TAG,"soundPoolMap.load bgm");
	    //
	    soundPoolMap.put(sound1, soundPool.load(this, R.raw.sound2, 1));
	    Log.i(TAG,"soundPoolMap.load sound1");
	   
	    
        home = (ImageButton) findViewById(R.id.home);
        menu = (ImageButton) findViewById(R.id.menu);
        
        
        /**
         * 这里必须要等资源加载完毕之后才能播放,不然会报错播放失败
         */
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            	playSound(bgm, -1);//0:no-loop,-1:loop-forever
            }
        });
        
        menu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				playSound(sound1, 0);//0:no-loop,-1:loop-forever
				
			}
		});

public void playSound(String soundName,int loop){
		AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);   
	    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);   
	    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);       
	    float volume = streamVolumeCurrent / streamVolumeMax;
	    Log.i(TAG, "streamVolumeCurrent:"+streamVolumeCurrent+" streamVolumeMax:"+streamVolumeMax);
	    
	    int sound_id=soundPoolMap.get(soundName);
	    Log.i(TAG, " soundPool.play:sound_id:"+sound_id);
	    if(0==soundPool.play(sound_id, volume, volume, 0, loop, 1f)){
	    	Log.e(TAG, "music play failed!");
	    }
	}

也没啥需要注意的,就是在记得一定要等资源加载好以后再播放。里面使用了OnLoadCompleteListener来处理。

资源如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值