想象一下:
睡前放松:想听音乐入睡,又不想整夜播放
课间休息:10分钟休息时间,到点自动停止
专注工作:番茄工作法,25分钟专注后自动提醒
v1.0.4版本实现的30分钟固定倒计时,正是为这些场景量身打造(后续实现倒计时事件可调)。

1. 需要增加3个状态变量:剩余秒数,是否激活,定时器引用。
// v1.0.4 倒计时功能相关状态@State countdownSeconds: number = 600; // 剩余秒数(10分钟=600秒)@State isCountdownActive: boolean = false; // 倒计时是否激活private countdownTimer: number | null = null; // 定时器引用
其中countdownTimer是JavaScript的定时器引用,使用时要注意正确管理,防止内存泄漏。
startCountdown()方法// v1.0.4 启动倒计时startCountdown() {// 1. 清理可能存在的旧计时器this.clearCountdown();// 2. 重置为10分钟并激活this.countdownSeconds = 600;this.isCountdownActive = true;// 3. 启动每秒更新的定时器this.countdownTimer = setInterval(() => {if (this.countdownSeconds > 0) {this.countdownSeconds--; // 每秒减1// 4. 倒计时结束处理if (this.countdownSeconds === 0) {this.stopAudio(); // 自动停止播放this.clearCountdown(); // 清理资源}}}, 1000);}
setInterval的特点:不需要递归调用,可随时停止(clearInterval),适合固定间隔的周期任务。
3. 状态机的变化:
async playRawFileAudio() {// ... 初始化播放器代码// v1.0.4 启动倒计时this.startCountdown(); // 播放开始时启动倒计时}
// 在倒计时结束回调中if (this.countdownSeconds === 0) {if (this.avPlayer && this.playerState === PlayerState.PLAYING) {this.stopAudio(); // 自动调用stop()方法}}

clearCountdown() {if (this.countdownTimer) {clearInterval(this.countdownTimer); // 必须清理!this.countdownTimer = null;}}
aboutToDisappear() {this.clearCountdown(); // 必须调用this.releasePlayer();}