开发者

SoundPool slowing down app

开发者 https://www.devze.com 2023-03-13 15:31 出处:网络
I have a class called Sound.java that consists of 3 functions (initSound, addSound, and playSound). public static void initSound(Context con) {

I have a class called Sound.java that consists of 3 functions (initSound, addSound, and 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);
}

I called the initSound and addSound in the MainGame.java constructor.

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

and called playSound inside a Thread (looping) in MainGame.java. PlaySound called every second when an event is triggered (for example, when an enemy is in sight, troops (more than one) will shoot (play the sound) continuously until the enemy is dead).

Sound.playSound(1);

The problem is when the sound plays, the app is slowing down. I'm using soundpool because as far as I know for sound effects, soundpool is better than mediaplayer. (I've tried mediaplayer and the lag is even more.)

The s开发者_运维知识库ound file that I use is .wav (unsigned 8bit PCM, 1 Channel, 8000hz) with size 5.44KB.

Is there a better way to play effect sounds without slowing the game performance, or is mine wrong? I really appreciate any ideas and responses.


According to the SoundPool docs, it decodes to 16-bit PCM, so you could change to that and see if you get some performance out of that. Other than that, your code seems pretty similar (at least as far as I can remember) to stuff I've done before and I didn't see any significant perf problems (I believe I wasn't even using WAV, I was just using OGGs, but I don't remember for sure). Are you trying this on an actual device, or just the emulator?


I had the same problem. Then I've created a new thread for the soundpool and added 20ms sleep into the while loop. The problem is gone.

0

精彩评论

暂无评论...
验证码 换一张
取 消