2012-04-16 88 views
6

我目前正面臨着我的Android遊戲的一個問題。通常當調用SoundPool.play()函數需要大約0.003秒完成,但有時需要0.2秒,這使我的遊戲口吃。他的異常來自哪裏?Android SoundPool.play()有時會延遲

+0

我們展示一些代碼,可能有一定的幫助。不知道你的遊戲有什麼我有預感它可能是線程相關的。 – Aidanc 2012-04-16 21:15:13

+0

好吧,它有點複雜的代碼,你想看什麼? – 2012-04-16 21:15:56

+0

你如何處理應用程序中的線程? – Aidanc 2012-04-16 21:16:39

回答

5

感謝蒂姆,使用線程播放似乎成功解決了問題。

主題

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