2012-04-16 25 views
6

Tôi hiện đang gặp sự cố với trò chơi Android của mình. Thông thường khi gọi SoundPool.play() chức năng cần khoảng 0,003 giây để hoàn thành, nhưng đôi khi phải mất 0,2 giây làm cho trò chơi của tôi nói lắp. nơi có thể bất thường của ông đến từ đâu?Android SoundPool.play() đôi khi thua

+0

Hiện chúng tôi một số mã có thể giúp đỡ một số. Mà không biết bất cứ điều gì về trò chơi của bạn tôi có linh cảm nó có thể là chủ đề liên quan. – Aidanc

+0

tốt, nó bằng cách nào đó mã phức tạp, những gì bạn muốn xem? –

+0

Bạn xử lý luồng trong ứng dụng như thế nào? – Aidanc

Trả lời

5

nhờ Tim, sử dụng Chủ đề để phát dường như giải quyết sự cố thành công.

Chủ đề

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; 
    } 
} 
Các vấn đề liên quan