播放简短的 .wav 文件 - Android [英] Playing short .wav files - Android

查看:26
本文介绍了播放简短的 .wav 文件 - 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 是正确的类.下面的代码是如何使用它的示例.这也是我在我的几个应用程序中用来管理声音的代码.您可以随心所欲(或在记忆力允许的情况下).

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;
    }
}

您可以通过调用来使用它:

You would use this by calling:

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 文件 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆