yumi-flutter/lib/shared/tools/sc_lucky_gift_win_sound_player.dart
2026-05-07 10:06:02 +08:00

63 lines
1.7 KiB
Dart

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart';
class SCLuckyGiftWinSoundPlayer {
static const String assetPath =
"sc_images/room/anim/luck_gift/lucky_gift_win.mp3";
static const Duration _sameEventDedupeWindow = Duration(seconds: 3);
static final AudioPlayer _player = AudioPlayer();
static String? _lastEventKey;
static DateTime? _lastPlayedAt;
static String buildEventKey({
String? giftId,
String? userId,
String? toUserId,
num? awardAmount,
}) {
return [
(giftId ?? '').trim(),
(userId ?? '').trim(),
(toUserId ?? '').trim(),
_formatNum(awardAmount),
].join('|');
}
static Future<void> play({String? eventKey}) async {
if (DataPersistence.getPlayGiftMusic()) {
return;
}
final normalizedEventKey = (eventKey ?? '').trim();
final now = DateTime.now();
final lastPlayedAt = _lastPlayedAt;
if (normalizedEventKey.isNotEmpty &&
normalizedEventKey == _lastEventKey &&
lastPlayedAt != null &&
now.difference(lastPlayedAt) < _sameEventDedupeWindow) {
return;
}
_lastEventKey = normalizedEventKey.isEmpty ? null : normalizedEventKey;
_lastPlayedAt = now;
try {
await _player.stop();
await _player.play(AssetSource(assetPath));
} catch (error) {
debugPrint('播放幸运礼物中奖音效失败: $error');
}
}
static String _formatNum(num? value) {
if (value == null) {
return '';
}
if (value % 1 == 0) {
return value.toInt().toString();
}
return value.toString();
}
}