播放短的.wav文件 - 安卓

16

我希望在触摸按钮后播放声音。MediaPlayer 可以正常使用,但我在某处读到这个库适用于长音频(如音乐)。

有更好的方法来播放2-3秒钟的短wav文件吗?


4
没错,SoundPool是一个好的选择。 - Kevin Coppock
1个回答

29

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();

释放资源。


它运行得非常好,但我有两个问题。1. 我必须在每次使用后释放(像MediaPlayer一样),还是在我退出应用程序/活动时?2. 有没有办法停止示例? - CookieMonssster
你应该在整个应用程序会话中播放完所有声音后才释放它(因此onDestroy()是一个不错的选择)。你可以添加一个pause()方法,使用SoundPools的pause()方法 - Raghav Sood
这很容易。顺便说一下,Eclipse建议使用SparseIntArray()来代替mSounds以获得更好的性能,所以我就这么做了。 - Mark Cramer
1
在我来自的未来,SoundPool已被弃用。查看此链接以获取更多答案:https://dev59.com/5kzSa4cB1Zd3GeqPoJwq - Yaroslav
2
Soundpool并未被弃用,您只需要使用Builder来构造对象,而不是自己创建新实例。 - Vladimir Marton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接