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(); Future init() async { print('初始化 AudioService'); if (_isInitialized) { print('AudioService 已经初始化'); return this; } await _cleanupExistingService(); try { // 使用锁确保初始化的原子性 await _lock.synchronized(() async { if (_isInitialized) return; // 初始化 AudioService _audioHandler = await AudioService.init( builder: () => MyAudioHandler(), config: const AudioServiceConfig( androidNotificationChannelId: 'com.example.deep_voice.channel.audio', androidNotificationChannelName: 'Deep Voice Audio Service', androidNotificationIcon: 'drawable/ic_notification', androidNotificationOngoing: true, androidStopForegroundOnPause: true, androidShowNotificationBadge: true, notificationColor: Colors.blue, ), ); _isInitialized = true; }); return this; } catch (e) { print('AudioService初始化失败: $e'); await _cleanupExistingService(); rethrow; } } Future _cleanupExistingService() async { _isInitialized = false; // 停止现有的音频处理器 if (_audioHandler != null) { await _audioHandler!.stop(); _audioHandler = null; } // 停止 AudioService try { await AudioService.stop(); } catch (e) { print('停止 AudioService 时出错: $e'); } // 等待一小段时间确保清理完成 await Future.delayed(const Duration(milliseconds: 100)); } @override void onClose() async { await _cleanupExistingService(); super.onClose(); } }