1
這裏是我的代碼:的Soundpool加載永遠不會結束
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
public class GameActivity extends Activity implements OnGestureListener, OnInitListener {
private SoundPool soundPool;
private int wallSound, moveSound, completeSound, restartSound, readysetgoSound;
boolean loaded = false;
float actualVolume, maxVolume, volume;
GestureDetector gDetector;
Vibrator vibrator;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gDetector = new GestureDetector(this);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
wallSound = soundPool.load(this, R.raw.wall, 1);
moveSound = soundPool.load(this, R.raw.move, 1);
completeSound = soundPool.load(this, R.raw.complete, 1);
restartSound = soundPool.load(this, R.raw.restart, 1);
readysetgoSound = soundPool.load(this, R.raw.readysetgo, 1);
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume/maxVolume;
while (!loaded) {
Log.e("Load Status", "Loading...");
}
}
public void onStart() {
super.onStart();
while(soundPool.play(readysetgoSound, volume, volume, 1, 0, 1f) == 0) {}
}
...
我遇到我的時候聲音文件被加載時檢查的問題。在onCreate
方法中,注意最後一個while循環。理論上,據我所知,一旦聲音被加載,代碼應該繼續。但是,該應用程序永遠不會離開while循環,並且會一直持續循環。我相信我可能會誤解onLoadCompleteListener
的SoundPool
並且執行不正確。我想確保我的應用程序不會離開onCreate
方法,直到完全加載所有五個聲音。
我發現,以確保只有一次它被加載我想播放聲音的唯一方法是通過使用onStart
方法顯示while循環。在加載之前,play
方法始終返回零。但是,我不喜歡這種方法,因爲每次我想要播放聲音時都必須使用它。也可能非常低效。