import 'dart:async'; import 'package:audio_service/audio_service.dart'; import 'package:get/get.dart'; import 'package:flutter/material.dart'; import 'package:synchronized/synchronized.dart'; import 'my_audio_handler.dart'; class AudioServiceManager extends GetxService { static AudioServiceManager get to => Get.find(); MyAudioHandler? _audioHandler; bool _isInitialized = false; final _lock = Lock(); // 添加一个标志,表示是否已经尝试过初始化 bool _hasAttemptedInit = false; Future init() async { print('初始化 AudioServiceManager'); if (_isInitialized) { print('AudioServiceManager 已经初始化'); return this; } // 如果已经尝试过初始化但失败了,不再重试 if (_hasAttemptedInit) { print('AudioServiceManager 之前初始化失败,不再重试'); return this; } _hasAttemptedInit = true; try { // 使用锁确保初始化的原子性 await _lock.synchronized(() async { if (_isInitialized) return; // 使用 AudioService.init 初始化音频服务 _audioHandler = await AudioService.init( builder: () => MyAudioHandler(), config: AudioServiceConfig( androidNotificationChannelId: 'com.example.deep_voice.channel.audio', androidNotificationChannelName: 'Deep Voice Audio Service', // 使用新创建的通知图标 androidNotificationIcon: 'drawable/ic_notification', // 设置为 false,避免在没有用户交互时启动前台服务 androidNotificationOngoing: false, // 设置为 true,当暂停时停止前台服务 androidStopForegroundOnPause: true, androidShowNotificationBadge: true, notificationColor: Colors.blue, // 设置为 false,避免自动启动前台服务 fastForwardInterval: const Duration(seconds: 10), rewindInterval: const Duration(seconds: 10), preloadArtwork: false, ), ); // 注册自定义音频处理器 await Get.put(_audioHandler!, permanent: true); _isInitialized = true; print('AudioServiceManager 初始化成功'); }); return this; } catch (e) { print('AudioServiceManager初始化失败: $e'); _isInitialized = false; // 确保失败时重置状态 return this; // 即使失败也返回实例,避免空指针异常 } } // 获取音频处理器 MyAudioHandler? get audioHandler => _audioHandler; // 发送媒体按钮事件 Future sendMediaButtonEvent() async { if (_audioHandler != null) { try { await _audioHandler!.customAction('media_button'); } catch (e) { print('发送媒体按钮事件失败: $e'); } } else { print('AudioHandler 未初始化,无法发送媒体按钮事件'); } } @override void onClose() async { _isInitialized = false; // 停止现有的音频处理器 if (_audioHandler != null) { try { await _audioHandler!.stop(); } catch (e) { print('停止 AudioHandler 失败: $e'); } _audioHandler = null; } super.onClose(); } }