Waiting for SoundPool to load before moving on with application

后端 未结 4 747
慢半拍i
慢半拍i 2020-12-20 22:39

I was following a tutorial to integrate SoundPool into my app, and this is the code which was given in the tutorial:

package com.example.soundpoolexample;

i         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 23:12

    You can have an elegant solution using Semaphore, however try to avoid blocking onCreate(), since the app will not be responsive, the code here is just to illustrate the use of Semaphore

    public class SoundPoolExample extends Activity implements OnTouchListener {
    
    public static final Semaphore semaphore = new Semaphore(0);
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId,
                    int status) {
    
                semaphore.release();
            }
        });
        soundID = soundPool.load(this, R.raw.sound1, 1);
    
        // Will block since there is not permits (the semaphore is initialized with 0)
        // then will continue once semaphore.release(); is called i.e. after loading is finished
        semaphore.acquire();
    } 
    
    // rest of your class
    
    }
    

提交回复
热议问题