1.MediaPlay与SoundPool
MediaPlay会占用大量的系统资源,而且播放时还需要进行缓冲,有较大的延时,MediaPlay无法实现即时音效。
SoundPool将声音资源加载到内存中,然后在需要的时候进行即时播放,几乎没有延时。对于同一个音效文件,在不改变其时长的情况下,
可以采用降低采样率或由立体声改成单声道的方式来缩小体积。
SoundPool实例:
public class SoundPoolActivity extends Activity {
/** Called when the activity is first created. */
private SoundPool sp;
private HashMap<Integer,Integer> hm;
int currStreamId;
private Button start ,stop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iniSoundPool();
start=(Button)findViewById(R.id.startButton);
stop=(Button)findViewById(R.id.stopButton);
start.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
playSound(1,0);
Toast.makeText(getApplicationContext(), "播放音效", Toast.LENGTH_SHORT).show();
}
});
stop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
sp.stop(currStreamId);
Toast.makeText(getApplicationContext(), "停止播放", Toast.LENGTH_SHORT).show();
}
});
}
private void iniSoundPool() {
sp = new SoundPool(2,AudioManager.STREAM_MUSIC,0);
hm=new HashMap<Integer,Integer>();
hm.put(1, sp.load(this, R.raw.musictest,1));
}
private void playSound(int sound, int loop) {
AudioManager am=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent=am.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax=am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume=streamVolumeCurrent/streamVolumeMax;
currStreamId=sp.play(hm.get(sound), volume, volume, 1, loop, 1.0f);
}
}
注:MediaPlay较适合做游戏背景音效