Android SoundPool.play()有时会滞后

问题描述 投票:6回答:1

我目前在我的Android游戏中遇到问题。通常,在调用SoundPool.play()时,该功能大约需要0.003秒才能完成,但有时需要0.2秒,这会使我的游戏变得停顿。他的异常来自何处?

android soundpool
1个回答
6
投票

感谢Tim,使用线程进行播放似乎可以成功解决此问题。

线程

package org.racenet.racesow.threads;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.racenet.racesow.models.SoundItem;

import android.media.SoundPool;

/**
 * Thread for playing sounds
 * 
 * @author soh#zolex
 *
 */
public class SoundThread extends Thread {

    private SoundPool soundPool;
    public BlockingQueue<SoundItem> sounds = new LinkedBlockingQueue<SoundItem>();
    public boolean stop = false;

    /**
     * Constructor
     * 
     * @param soundPool
     */
    public SoundThread(SoundPool soundPool) {

        this.soundPool = soundPool;
    }

    /**
     * Dispose a sound
     * 
     * @param soundID
     */
    public void unloadSound(int soundID) {

        this.soundPool.unload(soundID);
    }

    @Override
    /**
     * Wait for sounds to play
     */
    public void run() {         

        try {

            SoundItem item;
            while (!this.stop) {

                item = this.sounds.take();
                if (item.stop) {

                    this.stop = true;
                    break;
                }

                this.soundPool.play(item.soundID, item.volume, item.volume, 0, 0, 1);
            }

        } catch (InterruptedException e) {}
    }
}

SoundItem

package org.racenet.racesow.models;

/**
 * SoundItem will be passed to the SoundThread which
 * will handle the playing of sounds
 * 
 * @author soh#zolex
 *
 */
public class SoundItem {

    public int soundID;
    public float volume;
    public boolean stop = false;

    /**
     * Default constructor
     * 
     * @param soundID
     * @param volume
     */
    public SoundItem(int soundID, float volume) {

        this.soundID = soundID;
        this.volume = volume;
    }

    /**
     * Constructor for the item
     * which will kill the thread
     * 
     * @param stop
     */
    public SoundItem(boolean stop) {

        this.stop = stop;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.