我想在按下按钮后播放声音。MediaPlayer运行得很好,但我在某处读到这个库是用于长.wav的(比如音乐)。
有没有更好的方法来玩短.wav(2-3秒)?
发布于 2012-12-15 03:34:57
对于这一点,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);
在您的活动的onCreate()中(或之后的任何时间)。之后,播放一个声音简单的呼叫:
sound.playShortResource(R.raw.<sound_name>);
最后,听完声音后,调用:
sound.release();
来释放资源。
https://stackoverflow.com/questions/13883883
复制相似问题