109 lines
2.8 KiB
Dart
109 lines
2.8 KiB
Dart
import 'package:audioplayers/audioplayers.dart';
|
||
import 'package:shared_preferences/shared_preferences.dart';
|
||
|
||
/// 时间: 2026-03-30
|
||
/// 功能: 音频管理类
|
||
/// 介绍: 管理应用中的音效播放,包括点击音效、点赞音效等
|
||
/// 最新变化: 重写声音播放逻辑,确保声音正常播放,不依赖GlobalAudioScope
|
||
|
||
class AudioManager {
|
||
static AudioManager? _instance;
|
||
bool _isInitialized = false;
|
||
bool _isMuted = false;
|
||
AudioPlayer? _player;
|
||
|
||
AudioManager._internal();
|
||
|
||
factory AudioManager() {
|
||
_instance ??= AudioManager._internal();
|
||
return _instance!;
|
||
}
|
||
|
||
Future<void> init() async {
|
||
if (_isInitialized) return;
|
||
|
||
try {
|
||
await _loadSoundSetting();
|
||
// 不依赖GlobalAudioScope的初始化,直接创建AudioPlayer
|
||
_player = AudioPlayer();
|
||
_isInitialized = true;
|
||
print('AudioManager初始化成功');
|
||
} catch (e) {
|
||
print('AudioManager初始化失败: $e');
|
||
_isInitialized = true;
|
||
}
|
||
}
|
||
|
||
/// 加载保存的声音设置
|
||
Future<void> _loadSoundSetting() async {
|
||
try {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
bool soundEnabled = prefs.getBool('sound_enabled') ?? true;
|
||
_isMuted = !soundEnabled;
|
||
print('声音设置: soundEnabled=$soundEnabled, _isMuted=$_isMuted');
|
||
} catch (e) {
|
||
print('加载声音设置失败: $e');
|
||
_isMuted = false;
|
||
}
|
||
}
|
||
|
||
/// 播放点击音效
|
||
void playClickSound() {
|
||
_playSound('audios/deep.mp3');
|
||
}
|
||
|
||
/// 播放点赞音效
|
||
void playLikeSound() {
|
||
_playSound('audios/deep.mp3');
|
||
}
|
||
|
||
/// 播放下一条音效
|
||
void playNextSound() {
|
||
_playSound('audios/deep.mp3');
|
||
}
|
||
|
||
/// 播放音频
|
||
void _playSound(String assetPath) {
|
||
if (_isMuted) {
|
||
print('声音已静音,不播放: $assetPath');
|
||
return;
|
||
}
|
||
print('播放声音: $assetPath');
|
||
_playSoundAsync(assetPath);
|
||
}
|
||
|
||
/// 异步播放音频
|
||
Future<void> _playSoundAsync(String assetPath) async {
|
||
try {
|
||
// 确保player已初始化
|
||
if (_player == null) {
|
||
_player = AudioPlayer();
|
||
}
|
||
|
||
// 播放音频
|
||
await _player!.play(AssetSource(assetPath));
|
||
print('声音播放成功: $assetPath');
|
||
} catch (e) {
|
||
print('声音播放失败: $assetPath, 错误: $e');
|
||
// 如果播放失败,尝试重新创建player
|
||
try {
|
||
_player?.dispose();
|
||
_player = AudioPlayer();
|
||
await _player!.play(AssetSource(assetPath));
|
||
print('声音重播成功: $assetPath');
|
||
} catch (retryError) {
|
||
print('声音重播失败: $assetPath, 错误: $retryError');
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 设置静音状态
|
||
void setMuted(bool muted) {
|
||
_isMuted = muted;
|
||
print('设置静音状态: $_isMuted');
|
||
}
|
||
|
||
/// 获取静音状态
|
||
bool get isMuted => _isMuted;
|
||
}
|