Files
observer/flutter_app/lib/reminder/reminder.dart
T
2026-09-03 17:50:23 +08:00

38 lines
1.0 KiB
Dart

import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:vibration/vibration.dart';
/// 提醒:同类目标 10s 内只提醒一次。
/// 震动/提示音默认开启,不提供关闭入口。
class Reminder {
// 惰性创建:AudioPlayer 构造即发起平台初始化(无插件环境下未处理错误会
// 泄漏为 unhandled async error),首响时才建
AudioPlayer? _player;
String? _lastAlertLabel;
int _lastAlertAt = 0;
/// 同类目标 10s 内只提醒一次
void onDetected(String label) {
final now = DateTime.now().millisecondsSinceEpoch;
if (label == _lastAlertLabel && now - _lastAlertAt < 10000) return;
_lastAlertAt = now;
_lastAlertLabel = label;
_vibrate();
_playTone();
}
void _vibrate() => Vibration.vibrate(duration: 200);
Future<void> _playTone() async {
final p = _player ??= AudioPlayer();
await p.stop();
await p.play(AssetSource('beep.wav'));
}
void release() {
_player?.dispose();
}
}