如何在Android中加速SoundPool?

时间:2016-01-14 15:18:34

标签: android soundpool

我正在尝试创建一个简单的摩尔斯电码应用程序。当用户按下按钮时,莫尔斯声音应该在释放之前开始。

问题是延迟 - 莫尔斯声音在用户按下按钮后大约400ms才开始。我不确定为什么这是确切的,但在研究问题后我认为这是我的代码结构的方式。我尝试播放的文件是Mp3格式,位于原始文件夹中。

我已经使用媒体播放器完成了这个但是我遇到了同样的问题,因为它没有足够的响应,所以我选择尝试使用声音池。有没有人对如何加快操作有任何意见/建议?在发展方面,这是我的新领域。

public int S1 = R.raw.morse;

private SoundPool soundPool;

private boolean loaded;

static int x;

public void initSounds(Context context) {

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

    final int y = soundPool.load(context, R.raw.morse, 1);

    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                                   int status) {
            loaded = true;

            playSound(y);

        }
    });
}


public void playSound(int soundID) {

    if(loaded) {
        x = soundPool.play(soundID, 0.5f, 0.5f, 1, 0, 1f);
    }

}

   //Calling code
   pad.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                //State of a toggle button
                if(audioOnOff==true) {

       //Sound pool object is created and initialized as a global variabe
                    sp.initSounds(getApplicationContext());

                }
             }

1 个答案:

答案 0 :(得分:1)

在我看来,这里发生的事情是,每次按下按钮,你都会加载声音,等待它完成加载,然后再播放。你真正想要的是加载声音一次,然后每按一次按钮就播放它。

因此,不要在onTouchListener中调用initSounds,而是在按下按钮之前在其他地方调用initSounds。然后在你的onTouchListener中你只需要调用你的playSound方法。

最后,请确保从onLoadCompleteListener中删除playSound方法调用,以便在最初加载声音时不会产生神秘的噪音;)

相关问题