现在编写一个简单的测试活动,每当单击屏幕时它就播放一个爆炸音效。代码如下:
package org.example.ch04_Android_basics;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class SoundPoolTest extends Activity implements OnTouchListener{
SoundPool soundPool;
int explosionId = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setOnTouchListener(this);
setContentView(textView);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
try{
AssetManager assetManager = getAssets();
AssetFileDescriptor descriptor = assetManager
.openFd("explosion.ogg");
explosionId = soundPool.load(descriptor, 1);
}catch(IOException e){
textView.setText("Couldn't load sound effect from asset, " +
e.getMessage());
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_UP){
if(explosionId != -1){
soundPool.play(explosionId, 1, 1, 0, 0, 1);
}
}
return true;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
soundPool.release();
}
}
SoundPool在处理MP3文件或长的音频文件时会有问题,长文件的定义超过5或6秒钟。一般建议使用OGG音频文件来代替MP3文件,并尽可能使用低的采样率和持续时间,同时保持音效质量。