我希望在触摸按钮后播放声音。MediaPlayer 可以正常使用,但我在某处读到这个库适用于长音频(如音乐)。
有更好的方法来播放2-3秒钟的短wav文件吗?
我希望在触摸按钮后播放声音。MediaPlayer 可以正常使用,但我在某处读到这个库适用于长音频(如音乐)。
有更好的方法来播放2-3秒钟的短wav文件吗?
SoundPool是正确的类,以下代码是如何使用它的示例。这也是我在几个应用程序中用来管理声音的代码。您可以拥有尽可能多的声音(或内存允许的数量)。
public class SoundPoolPlayer {
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();
public SoundPoolPlayer(Context pContext)
{
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSounds.put(R.raw.<sound_1_name>, this.mShortPlayer.load(pContext, R.raw.<sound_1_name>, 1));
mSounds.put(R.raw.<sound_2_name>, this.mShortPlayer.load(pContext, R.raw.<sound_2_name>, 1));
}
public void playShortResource(int piResource) {
int iSoundId = (Integer) mSounds.get(piResource);
this.mShortPlayer.play(iSoundId, 0.99f, 0.99f, 0, 0, 1);
}
// Cleanup
public void release() {
// Cleanup
this.mShortPlayer.release();
this.mShortPlayer = null;
}
}
通过调用此函数来使用:
SoundPoolPlayer sound = new SoundPoolPlayer(this);
在您的Activity的onCreate()方法中(或在此之后的任何时间)。之后,要播放声音,只需调用:
sound.playShortResource(R.raw.<sound_name>);
最后,当你完成声音时,请调用:
sound.release();
释放资源。
SparseIntArray()
来代替mSounds
以获得更好的性能,所以我就这么做了。 - Mark Cramer
SoundPool
是一个好的选择。 - Kevin Coppock