SoundPool减慢app

时间:2011-06-17 20:41:47

标签: android performance soundpool

我有一个名为Sound.java的类,它由3个函数组成(initSound,addSound和playSound)。

public static void initSound(Context con) {
    mContext = con;
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    soundPoolMap = new HashMap<Integer, Integer>();
    audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
    streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    streamVolume = streamVolume / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}

public static void addSound(int index, int SoundID) {
    soundPoolMap.put(index, soundPool.load(mContext, SoundID, 1));
}

public static void playSound(int index) {
    soundPool.play(soundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}

我在MainGame.java构造函数中调用了initSound和addSound。

Sound.initSound(getContext());
Sound.addSound(1, R.raw.machine_gun);

并在MainGame.java中的一个Thread(循环)中调用了playSound。当一个事件被触发时,PlaySound每秒都会调用一次(例如,当敌人在视线中时,部队(不止一个)将持续射击(播放声音)直到敌人死亡)。

Sound.playSound(1);

问题是当声音播放时,应用程序正在放慢速度。 我正在使用soundpool,因为就我所知的音效而言,soundpool比mediaplayer更好。 (我已尝试过媒体播放器,而且滞后更多。)

我使用的声音文件是.wav(无符号8位PCM,1通道,8000hz),大小为5.44KB。

有没有更好的方法来播放效果声音而不会降低游戏性能,或者我的错误?我真的很感激任何想法和回应。

2 个答案:

答案 0 :(得分:0)

根据SoundPool docs,它解码为16位PCM,所以你可以改为那个,看看你是否从中获得了一些性能。除此之外,你的代码看起来非常相似(至少在我记忆中)我之前做过的事情,我没有看到任何明显的性能问题(我相信我甚至没有使用WAV,我只是使用OGG,但我不记得肯定)。您是在实际设备上尝试此操作,还是只在模拟器上尝试?

答案 1 :(得分:0)

我遇到了同样的问题。然后我为soundpool创建了一个新线程,并在while循环中添加了20ms sleep。问题消失了。

相关问题