这是我的代码:
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
forSoundPool
并错误地实施它。我想确保在onCreate
完全加载所有五个声音之前,我的应用程序不会离开该方法。
我发现确保我想要的声音仅在加载后才播放的唯一方法是使用onStart
方法中显示的 while 循环。在加载之前,该play
方法始终返回零。但是,我不喜欢这种方法,因为每次我想播放声音时都必须使用它。可能效率也很低。