主要还是希望开箱即用。所以才有了这篇,也是备忘。
以下代码适合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来处理。
资源如下: