0

我有一个名为 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 的线程(循环)中调用 playSound。PlaySound 在事件触发时每秒调用一次(例如,当一个敌人在视线范围内时,部队(不止一个)将连续射击(播放声音)直到敌人死亡)。

Sound.playSound(1);

问题是当声音播放时,应用程序变慢了。我使用 soundpool 是因为据我所知的音效,soundpool 比 mediaplayer 更好。(我已经尝试过媒体播放器,但延迟更大。)

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

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

4

2 回答 2

0

根据SoundPool 文档,它解码为 16 位 PCM,因此您可以更改为 16 位 PCM,看看是否能从中获得一些性能。除此之外,您的代码似乎与我之前做过的东西非常相似(至少据我所知),而且我没有看到任何重大的性能问题(我相信我什至没有使用 WAV,我只是使用OGG,但我不记得了)。您是在实际设备上尝试,还是仅在模拟器上尝试?

于 2011-06-17T22:07:38.283 回答
0

我有同样的问题。然后我为声音池创建了一个新线程,并在 while 循环中添加了 20 毫秒的睡眠时间。问题消失了。

于 2013-01-21T09:12:06.667 回答