播放短.wav文件 - 安卓 [英] Playing short .wav files - Android
问题描述
我想触摸按钮后,播放的声音。 MediaPlayer的工作正常,但我读的地方,这个库是长期.WAV(如音乐)。
I would like to play sound after touching the button. MediaPlayer works fine, but I read somewhere that this library is for long .wav (like music).
有没有更好的方式来播放.WAV短(2-3秒)?
Is there any better way to play short .wav(2-3 sec.)?
推荐答案
在的Soundpool 是正确的类此。下面code是如何使用它的示例。这也是code我用我的几个应用程序来管理的声音。你可以在5月的声音,只要你喜欢(或内存许可证)。
The SoundPool is the correct class for this. The below code is an example of how to use it. It is also the code I use in several apps of mine to manage the sounds. You can have as may sounds as you like (or as memory permits).
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()(或之后任何时候的话)。在这之后,播放声音简单的调用:
in your Activity's onCreate() (or anytime after it). After that, to play a sound simple call:
sound.playShortResource(R.raw.<sound_name>);
最后,一旦你的声音做了,叫:
Finally, once you're done with the sounds, call:
sound.release();
要释放资源。
这篇关于播放短.wav文件 - 安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!