我试图弄清楚如何将音频文件延迟大约15秒。音频文件是5秒长,它的声音效果是" 5,4,3,2,1 go!",倒计时是20,所以它应该在15秒后开始。我听说我可以用处理程序来做这件事,但我不知道如何在代码中实现它,所以在这里,非常感谢帮助!
我用下面的方式编辑了它,但现在播放器根本没有开始,这里是新代码:
public class WorkoutGymEasy1 extends Activity {
CountDownTimer cdt = null;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_gym_easy1);
RelativeLayout rl5 = (RelativeLayout) findViewById(R.id.rl5);
rl5.setBackgroundColor(Color.BLACK);
mp = MediaPlayer.create(WorkoutGymEasy1.this, R.raw.countdown);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new CountDownTimer(20000, 1000) { //20 seconds count down with 1s interval (1000 ms)
TextView c = (TextView) findViewById(R.id.timer_gym_easy1); //access TextView element on the screen to set the timer value
public void onTick(long millisUntilFinished) { // Code in this method is executed every 1000ms (1s)
c.setText("" + ((millisUntilFinished / 1000) - 1) + ""); //update the timer
if(millisUntilFinished == 9000) {
mp.start();
}
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
c.setText("GO!");
Intent myIntent = new Intent(getApplicationContext(), WorkoutGymEasy2.class);
startActivity(myIntent);
finish(); // call finish() method to destroy this activity and return to instructions screen
}
}.start();
}
protected void OnPause() {
super.onPause();
mp.release();
finish();
}
}
答案 0 :(得分:2)
请勿在{{1}}中播放音频。从onCreate()
移除mp.start()
。
onCreate()
在mp = MediaPlayer.create(WorkoutGymEasy1.this, R.raw.countdown);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
中播放音频。 onTick()
不准确,它会尽可能接近1秒。它永远不会是20000,19000 ......等。作为优化,您可以围绕每个CountDownTimer
上的millisUntilFinished
并进行简单检查,看看是否应该播放音频。
onTick()