98 lines
2.2 KiB
Dart
98 lines
2.2 KiB
Dart
import 'package:audioplayers/audioplayers.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
/// 时间: 2026-03-30
|
|
/// 功能: 音频管理类
|
|
/// 介绍: 管理应用中的音效播放,包括点击音效、点赞音效等
|
|
/// 最新变化: 新增音频播放功能
|
|
|
|
class AudioManager {
|
|
static AudioManager? _instance;
|
|
late AudioPlayer _audioPlayer;
|
|
bool _isInitialized = false;
|
|
bool _isMuted = false;
|
|
|
|
AudioManager._internal() {
|
|
_audioPlayer = AudioPlayer();
|
|
}
|
|
|
|
factory AudioManager() {
|
|
_instance ??= AudioManager._internal();
|
|
return _instance!;
|
|
}
|
|
|
|
Future<void> init() async {
|
|
if (_isInitialized) return;
|
|
|
|
try {
|
|
// 设置音频播放器模式
|
|
await _audioPlayer.setPlayerMode(PlayerMode.lowLatency);
|
|
_isInitialized = true;
|
|
_debugLog('音频管理器初始化成功');
|
|
} catch (e) {
|
|
_debugLog('音频管理器初始化失败: $e');
|
|
}
|
|
}
|
|
|
|
/// 播放点击音效
|
|
Future<void> playClickSound() async {
|
|
if (_isMuted) return;
|
|
await _playSound('audios/deep.mp3');
|
|
}
|
|
|
|
/// 播放点赞音效
|
|
Future<void> playLikeSound() async {
|
|
if (_isMuted) return;
|
|
await _playSound('audios/deep.mp3');
|
|
}
|
|
|
|
/// 播放下一条音效
|
|
Future<void> playNextSound() async {
|
|
if (_isMuted) return;
|
|
await _playSound('audios/deep.mp3');
|
|
}
|
|
|
|
/// 通用播放方法
|
|
Future<void> _playSound(String assetPath) async {
|
|
if (!_isInitialized) {
|
|
await init();
|
|
}
|
|
|
|
try {
|
|
// 停止当前播放的音频
|
|
await _audioPlayer.stop();
|
|
// 播放新音频
|
|
await _audioPlayer.play(AssetSource(assetPath));
|
|
_debugLog('播放音效: $assetPath');
|
|
} catch (e) {
|
|
_debugLog('播放音效失败: $e');
|
|
}
|
|
}
|
|
|
|
/// 设置静音状态
|
|
void setMuted(bool muted) {
|
|
_isMuted = muted;
|
|
_debugLog('静音状态: $_isMuted');
|
|
}
|
|
|
|
/// 获取静音状态
|
|
bool get isMuted => _isMuted;
|
|
|
|
/// 释放资源
|
|
Future<void> dispose() async {
|
|
try {
|
|
await _audioPlayer.dispose();
|
|
_isInitialized = false;
|
|
_debugLog('音频管理器已释放');
|
|
} catch (e) {
|
|
_debugLog('释放音频管理器失败: $e');
|
|
}
|
|
}
|
|
|
|
void _debugLog(String message) {
|
|
if (kDebugMode) {
|
|
print('[AudioManager] $message');
|
|
}
|
|
}
|
|
}
|