我正在尝试使用SoundPool播放sound.wav,然后使用CountDownTimer来控制播放声音的时间。我跑了代码,声音播放清晰。问题是,无论我输入什么“millisInFuture”,似乎根本不会触发CountDownTimer的onFinish / onTick功能(因此SoundPool根本没有停止,声音连续不停地播放)。我抓住了以下重要细节:
SoundPool初始化如下:
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(37);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
builder.setAudioAttributes(attrBuilder.build());
soundPool = builder.build();
,并加载了一些sound.wav:
resId = getResId(instrument, "c5", packageName);
c5 = soundPool.load(ctx, resId, 1);
变量值初始化如下:
duration = 250;
INTERVAL = 5;
代码:
public void play(long duration, float volume){
float currentVolume = volume;
stream = soundPool.play(id, currentVolume, currentVolume, 1, -1, 1f); // Sound is playing clearly and continuously without stopping
Log.i("Note.Play","Note now playing id=" + id); // I can see this in the run/debug log
new CountDownTimer(duration, INTERVAL) {
public void onTick(long millisUntilFinished) {
Log.i("CountDownTimer","CountDownTimer now checking the SoundPool to play "); // I can NOT see this in the run/debug log
}
public void onFinish() {
Log.i("CountDownTimer","FCountDownTimer now stopping the SoundPool to play"); // I can NOT see this in the run/debug log
soundPool.stop(stream);
isIdle = true;
}
}.start();
}
任何人都知道我做错了什么?或者我可以检查什么以了解原因?
延迟更新: 我只是发现失败是因为我在Main()线程中放了一个while循环来接收“isIdle”的状态(以便检测声音是否完成播放)。那么有没有办法让void play(,)函数通知Main()线程CountDownTimer已经完成并继续播放下一个声音?
感谢。