首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >播放短.wav文件-安卓

播放短.wav文件-安卓
EN

Stack Overflow用户
提问于 2012-12-15 01:55:12
回答 1查看 17.2K关注 0票数 16

我想在按下按钮后播放声音。MediaPlayer运行得很好,但我在某处读到这个库是用于长.wav的(比如音乐)。

有没有更好的方法来玩短.wav(2-3秒)?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-15 03:34:57

对于这一点,SoundPool是正确的类。下面的代码是如何使用它的示例。这也是我在我的几个应用中用来管理声音的代码。你可以有你喜欢的声音(或者在内存允许的情况下)。

代码语言:javascript
运行
复制
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;
    }
}

您可以通过调用以下命令来使用它:

代码语言:javascript
运行
复制
SoundPoolPlayer sound = new SoundPoolPlayer(this); 

在您的活动的onCreate()中(或之后的任何时间)。之后,播放一个声音简单的呼叫:

代码语言:javascript
运行
复制
sound.playShortResource(R.raw.<sound_name>);

最后,听完声音后,调用:

代码语言:javascript
运行
复制
sound.release();

来释放资源。

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13883883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档