You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中circular_countdown_timer倒计时最后5秒触发Tic音效实现咨询

实现圆形倒计时最后5秒每秒播放"Tic"音效的方案

1. 添加音频播放依赖

需要借助audioplayers包处理音频播放,在pubspec.yaml中添加依赖:

dependencies:
  audioplayers: ^4.0.1 # 建议使用最新版本

2. 在业务逻辑层实现音效控制

在你的_soloModeLogic类中,添加音频播放器实例,并通过记录上一次播放的秒数避免重复触发音效:

import 'package:audioplayers/audioplayers.dart';

class SoloModeLogic {
  // 已有代码...
  final CountDownController countDownController = CountDownController();
  final AudioPlayer audioPlayer = AudioPlayer();
  int _lastPlayedSecond = -1; // 标记已播放过音效的秒数

  // 提前加载音频,避免首次播放卡顿
  Future<void> initAudio() async {
    // 假设音频文件路径为assets/audios/tic.mp3,需在pubspec.yaml中声明
    await audioPlayer.setSource(AssetSource('audios/tic.mp3'));
  }

  // 处理倒计时变化的回调逻辑
  void handleCountDownChange(String value) {
    int remainingSeconds = int.tryParse(value) ?? 0;
    // 当剩余时间在1-5秒,且当前秒数未播放过音效时触发播放
    if (remainingSeconds >= 1 && remainingSeconds <=5 && remainingSeconds != _lastPlayedSecond) {
      audioPlayer.play(AssetSource('audios/tic.mp3'));
      _lastPlayedSecond = remainingSeconds;
    }
    // 倒计时结束后重置标记,确保下次倒计时能正常触发
    if (remainingSeconds == 0) {
      _lastPlayedSecond = -1;
    }
  }

  // 页面销毁时释放播放器资源,避免内存泄漏
  void dispose() {
    audioPlayer.dispose();
  }
}

3. 绑定回调到CircularCountDownTimer

修改Widget代码,将onChange回调指向上面实现的handleCountDownChange方法:

Positioned(
  right: 0,
  left: 0,
  bottom: -25,
  child: CircularCountDownTimer(
    duration: _soloModeLogic.quizTime,
    initialDuration: 0,
    controller: _soloModeLogic.countDownController,
    width: 5.w,
    height: 7.h,
    ringColor: Colors.grey.shade400,
    ringGradient: null,
    fillColor: _soloModeLogic.isFreezeColor
        ? Colors.lightBlueAccent
        : Colors.red,
    fillGradient: null,
    backgroundColor: const Color(0xfff5f5f5),
    backgroundGradient: null,
    strokeWidth: 4.w,
    strokeCap: StrokeCap.butt,
    textStyle: TextStyle(
      fontSize: 20.sp,
      color: _soloModeLogic.isFreezeColor
          ? Colors.lightBlueAccent
          : Colors.red,
      fontWeight: FontWeight.bold,
    ),
    textFormat: CountdownTextFormat.S,
    isReverse: true,
    isReverseAnimation: false,
    isTimerTextShown: true,
    autoStart: true,
    onStart: () {},
    onChange: (v) => _soloModeLogic.handleCountDownChange(v), // 绑定回调
    onComplete: () =>
        _soloModeLogic.onTimeOut(context: context),
  ),
),

4. 配置音频资源路径

在pubspec.yaml中声明音频资源,确保Flutter能识别到文件:

flutter:
  assets:
    - assets/audios/tic.mp3

关键注意事项

  • 提前加载音频:在页面初始化(如State的initState方法)中调用_soloModeLogic.initAudio(),避免首次播放出现延迟。
  • 释放资源:在State的dispose方法中调用_soloModeLogic.dispose(),清理播放器资源防止内存泄漏。
  • 防重复播放:通过_lastPlayedSecond标记已播放的秒数,避免onChange多次触发同一秒的音效播放。

内容的提问来源于stack exchange,提问作者Raj A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:23:16