MediaPlayer 是多媒体包的一个 基本工具,但它一次只能处理一个音频或 视频文件.
如果只有少量的音频要播放,并且想要快速的性能,SoundPool 类可提供帮助, 它在底层使用了 MediaPlayer API
SoundPool 与 MediaPlayer 之间的一个区别是: SoundPool 是仅为处理本地媒体文件而设计的
以下提供一个加载和播放 简单声音的示例.
当示例程序启动时,创建 SoundPool 并向其中载入音采样,然后开始播放它们,蟋蟀叫声不停地循环播放,而其他采样在一定延迟之后播放,然后将自身设置为在相同延迟之后再次播放,
主要代码如下:
@Override
protected void onResume() {
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, SRC_QUALITY);
soundPool.setOnLoadCompleteListener(this);
aMgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
sid_background = soundPool.load(this, R.raw.crickets, PRIORITY); //蟋蟀
sid_chimp = soundPool.load(this, R.raw.chimp, PRIORITY);//黑猩猩
sid_rooster = soundPool.load(this, R.raw.rooster, PRIORITY);//公鸡
sid_roar = soundPool.load(this, R.raw.roar, PRIORITY);//怒吼
try {
AssetFileDescriptor afd = this.getAssets().openFd("dogbark.mp3"); // 狗叫声
sid_bark = soundPool.load(afd.getFileDescriptor(), 0, afd.getLength(), PRIORITY);
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
//sid_bark = soundPool.load("/mnt/sdcard/dogbark.mp3", PRIORITY);
super.onResume();
}
@Override
public void onLoadComplete(SoundPool sPool, int sid, int status) {
Log.v("soundPool", "sid " + sid + " loaded with status " + status);
final float currentVolume = ((float)aMgr.getStreamVolume(AudioManager.STREAM_MUSIC)) /
((float)aMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
if(status != 0)
return;
if(sid == sid_background) {
if(sPool.play(sid, currentVolume, currentVolume, PRIORITY, -1, 1.0f) == 0) {
Log.v("soundPool", "Failed to start sound");
}
} else if(sid == sid_chimp) {
queueSound(sid, 5000, currentVolume);
} else if(sid == sid_rooster) {
queueSound(sid, 6000, currentVolume);
} else if(sid == sid_roar) {
queueSound(sid, 12000, currentVolume);
} else if(sid == sid_bark) {
queueSound(sid, 7000, currentVolume);
}
}
private void queueSound(final int sid, final long delay, final float volume) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(soundPool == null) return;
if(soundPool.play(sid, volume, volume,PRIORITY, 0, 1.0f) == 0) {
Log.e("soundPool", "Failed to start sound (" + sid + ")");
}
queueSound(sid, delay, volume);
}
}, delay);
}
相关代码请参见 SoundPoolDemo_19_4 工程