【问题标题】:Android SoundPool.play() sometimes lagsAndroid SoundPool.play() 有时会滞后
【发布时间】:2012-04-16 21:14:04
【问题描述】:

我目前的 Android 游戏存在问题。通常在调用 SoundPool.play() 时,该函数需要大约 0.003 秒才能完成,但有时需要 0.2 秒,这使我的游戏卡顿。他的异常是从哪里来的?

【问题讨论】:

  • 向我们展示一些代码可能会有所帮助。在对您的游戏一无所知的情况下,我有一种预感,它可能与线程有关。
  • 嗯,有点复杂的代码,你想看什么?
  • 你是如何处理应用程序中的线程的?
  • 播放声音不涉及线程。受影响的声音正在 OnTouchListener 的 onTouch 事件中播放。
  • 尝试将您的 soundpool.play() 移动到单独的线程,或者更好地创建一个服务来为您处理整个声音池,并在需要时从 Activity 调用方法来触发播放事件。

标签: android soundpool


【解决方案1】:

感谢 Tim,使用 Thread 进行播放似乎成功地解决了这个问题。

线程

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) {}
    }
}

声音项目

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;
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 2018-11-13
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多