我创建了一个程序,它在 CountdownTimer 的每个 onTick 方法中重复调用媒体播放器
媒体播放器类
public class Buzzer extends Activity{
private MediaPlayer mp;
private AssetFileDescriptor descriptor;
private Context context;
public Buzzer(Context context){
super();
this.context=context;
}
public void playBeep(){
play("beep.mp3");
}
public void stop(){
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
}
private void play(String file){
try {
mp = new MediaPlayer();
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp.reset();
mp = new MediaPlayer();
}
descriptor= context.getAssets().openFd("audios/"+file);
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onResume(){
super.onResume();
}
public void onDestroy(){
mp.stop();
mp.release();
super.onDestroy();
}
}
//主要活动
public class Main extends Activity {
Timer timer;
Buzzer buzzer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buzzer=new Buzzer(Main.this);
timer=new Timer(24000,1000);
timer.start();
}
public class Timer extends CountDownTimer{
public ShotClock_CountdownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onTick (long millisUntilFinished) {
buzzer.playBeep();
}
public void onFinish() {
}
}
}