安卓SoundPool.play()有时会滞后 [英] Android SoundPool.play() sometimes lags

查看:333
本文介绍了安卓SoundPool.play()有时会滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正面临着与我的Andr​​oid游戏的一个问题。通常情况下调用SoundPool.play()函数需要约0.003秒完成,但有时,用0.2秒,这让我的比赛口吃的时候。在那里他能异常从何而来?

I'm currently facing an issue with my android game. Normally when calling SoundPool.play() the function needs about 0.003 seconds to finish, but sometimes it takes 0.2 seconds which makes my game stutter. where could his anomaly come from?

推荐答案

感谢Tim,使用线程播放似乎成功地解决该问题。

thanks to Tim, using a Thread for playing seemed to workaround the problem successfully.

主题

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 soundID;
    public volume;
    public 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;
    }
}

这篇关于安卓SoundPool.play()有时会滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆