audio_manager.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import 'package:flutter/services.dart';
  2. import 'package:flame_audio/flame_audio.dart';
  3. import 'dart:math';
  4. import 'dart:io' show Platform;
  5. import '../../utils/theme_manager.dart';
  6. class AudioManager {
  7. static final AudioManager _instance = AudioManager._internal();
  8. factory AudioManager() => _instance;
  9. AudioManager._internal();
  10. final Random _random = Random();
  11. bool _soundEnabled = true;
  12. bool _musicEnabled = true;
  13. bool _hapticEnabled = true;
  14. double _bgmVolume = 0.4; // 40% default
  15. double _sfxVolume = 0.6; // 60% default
  16. bool _isAudioSupported = false;
  17. bool _isVibrationSupported = false;
  18. AudioPool? _popPool;
  19. AudioPool? _popAltPool;
  20. // Current playing music context
  21. String? _currentMenuMusic;
  22. String? _currentIngameMusic;
  23. bool _isMenuMusic = false;
  24. // Available ingame music tracks by theme
  25. static const Map<String, List<String>> _ingameMusicTracks = {
  26. 'default': ['ingame/ingame_default_001.mp3'],
  27. 'spring': ['ingame/ingame_spring_001.mp3'],
  28. 'summer': ['ingame/ingame_summer_001.mp3'],
  29. 'autumn': ['ingame/ingame_autumn_001.mp3'],
  30. 'winter': ['ingame/ingame_winter_001.mp3', 'ingame/ingame_winter_002.mp3'],
  31. };
  32. bool get soundEnabled => _soundEnabled;
  33. bool get musicEnabled => _musicEnabled;
  34. bool get hapticEnabled => _hapticEnabled;
  35. double get bgmVolume => _bgmVolume;
  36. double get sfxVolume => _sfxVolume;
  37. bool get isAudioSupported => _isAudioSupported;
  38. bool get isVibrationSupported => _isVibrationSupported;
  39. Future<void> initialize() async {
  40. await _detectPlatformCapabilities();
  41. if (_isAudioSupported) {
  42. // Preload audio assets
  43. try {
  44. // Basic sound effects
  45. await FlameAudio.audioCache.loadAll([
  46. 'source/ambient_background.mp3',
  47. 'source/bubble_pop.mp3',
  48. 'source/bubble_pop_alt.mp3',
  49. ]);
  50. // Menu music files
  51. await FlameAudio.audioCache.loadAll([
  52. 'menu/menu_default.mp3',
  53. 'menu/menu_spring.mp3',
  54. 'menu/menu_summer.mp3',
  55. 'menu/menu_autumn.mp3',
  56. 'menu/menu_winter.mp3',
  57. ]);
  58. // Ingame music files
  59. final allIngameTracks = <String>[];
  60. for (final tracks in _ingameMusicTracks.values) {
  61. allIngameTracks.addAll(tracks);
  62. }
  63. await FlameAudio.audioCache.loadAll(allIngameTracks);
  64. // Create sound pools for efficient playback
  65. _popPool = await FlameAudio.createPool(
  66. 'source/bubble_pop.mp3',
  67. maxPlayers: 5,
  68. );
  69. _popAltPool = await FlameAudio.createPool(
  70. 'source/bubble_pop_alt.mp3',
  71. maxPlayers: 5,
  72. );
  73. } catch (e) {
  74. print('Failed to load audio assets or create pools: $e');
  75. }
  76. }
  77. print('AudioManager initialized for ${Platform.operatingSystem}');
  78. }
  79. Future<void> _detectPlatformCapabilities() async {
  80. // Check audio support
  81. _isAudioSupported = _checkAudioSupport();
  82. // Check vibration support
  83. _isVibrationSupported = _checkVibrationSupport();
  84. print(
  85. 'Platform capabilities - Audio: $_isAudioSupported, Vibration: $_isVibrationSupported',
  86. );
  87. }
  88. bool _checkAudioSupport() {
  89. try {
  90. // Just Audio supports Android, iOS, web, macOS, Windows and Linux
  91. // See: https://pub.dev/packages/just_audio
  92. return true;
  93. } catch (e) {
  94. print('Audio detection failed: $e');
  95. return false;
  96. }
  97. }
  98. bool _checkVibrationSupport() {
  99. try {
  100. // Only Android and iOS support vibration via HapticFeedback
  101. if (Platform.isAndroid || Platform.isIOS) {
  102. return true;
  103. }
  104. return false;
  105. } catch (e) {
  106. print('Vibration detection failed: $e');
  107. return false;
  108. }
  109. }
  110. void playBubblePop() {
  111. if (!_soundEnabled) return;
  112. // Make audio playback async to avoid blocking main thread
  113. _playBubblePopAsync();
  114. // Handle haptic feedback asynchronously
  115. if (_hapticEnabled && _isVibrationSupported) {
  116. _playHapticFeedbackAsync();
  117. }
  118. }
  119. void _playBubblePopAsync() async {
  120. if (_isAudioSupported) {
  121. // Use Flame Audio for bubble pop
  122. final sound =
  123. _random.nextBool()
  124. ? 'source/bubble_pop.mp3'
  125. : 'source/bubble_pop_alt.mp3';
  126. try {
  127. if (sound == 'source/bubble_pop.mp3' && _popPool != null) {
  128. _popPool!.start(volume: _sfxVolume);
  129. } else if (sound == 'source/bubble_pop_alt.mp3' &&
  130. _popAltPool != null) {
  131. _popAltPool!.start(volume: _sfxVolume);
  132. } else {
  133. // Fallback to direct playback if pools fail
  134. FlameAudio.play(sound, volume: _sfxVolume);
  135. }
  136. } catch (e) {
  137. print('Failed to play bubble pop sound: $e');
  138. }
  139. } else {
  140. // Fallback to system sound
  141. _playSystemSoundAsync();
  142. }
  143. }
  144. void _playSystemSoundAsync() async {
  145. try {
  146. // Vary the system sound for some variety
  147. final soundType = _random.nextInt(3);
  148. switch (soundType) {
  149. case 0:
  150. await SystemSound.play(SystemSoundType.click);
  151. break;
  152. case 1:
  153. await SystemSound.play(SystemSoundType.alert);
  154. break;
  155. default:
  156. await SystemSound.play(SystemSoundType.click);
  157. }
  158. } catch (e) {
  159. print('Failed to play system sound: $e');
  160. }
  161. }
  162. void _playHapticFeedbackAsync() async {
  163. if (!_isVibrationSupported) {
  164. // Silently skip haptic feedback on unsupported platforms
  165. return;
  166. }
  167. try {
  168. // Use Flutter's built-in HapticFeedback instead of vibration plugin
  169. await HapticFeedback.lightImpact();
  170. } catch (e) {
  171. print('Failed to play haptic feedback: $e');
  172. // Disable vibration support if it fails
  173. _isVibrationSupported = false;
  174. }
  175. }
  176. Future<void> playMenuMusic() async {
  177. if (!_musicEnabled || !_isAudioSupported) {
  178. if (!_isAudioSupported) {
  179. print('Menu music not available - using system audio only');
  180. }
  181. return;
  182. }
  183. try {
  184. // Get current theme
  185. final currentTheme = ThemeManager.effectiveTheme;
  186. final themeId = currentTheme.id;
  187. final menuMusicPath = 'menu/menu_$themeId.mp3';
  188. // Only change music if it's different from current
  189. if (_currentMenuMusic == menuMusicPath && _isMenuMusic) {
  190. print('Menu music already playing: $menuMusicPath');
  191. return;
  192. }
  193. // Stop any existing BGM first
  194. await FlameAudio.bgm.stop();
  195. // Play theme-based menu music
  196. FlameAudio.bgm.play(menuMusicPath, volume: _bgmVolume);
  197. _currentMenuMusic = menuMusicPath;
  198. _isMenuMusic = true;
  199. _currentIngameMusic = null;
  200. print('Menu music started: $menuMusicPath');
  201. } catch (e) {
  202. print('Failed to play menu music: $e');
  203. }
  204. }
  205. Future<void> playIngameMusic() async {
  206. if (!_musicEnabled || !_isAudioSupported) {
  207. if (!_isAudioSupported) {
  208. print('Ingame music not available - using system audio only');
  209. }
  210. return;
  211. }
  212. try {
  213. // Get current theme
  214. final currentTheme = ThemeManager.effectiveTheme;
  215. final themeId = currentTheme.id;
  216. // Get available tracks for this theme
  217. final availableTracks =
  218. _ingameMusicTracks[themeId] ?? _ingameMusicTracks['default']!;
  219. // Randomly select a track
  220. final selectedTrack =
  221. availableTracks[_random.nextInt(availableTracks.length)];
  222. // Only change music if it's different from current
  223. if (_currentIngameMusic == selectedTrack && !_isMenuMusic) {
  224. print('Ingame music already playing: $selectedTrack');
  225. return;
  226. }
  227. // Stop any existing BGM first
  228. await FlameAudio.bgm.stop();
  229. // Play randomly selected ingame music
  230. FlameAudio.bgm.play(selectedTrack, volume: _bgmVolume);
  231. _currentIngameMusic = selectedTrack;
  232. _isMenuMusic = false;
  233. _currentMenuMusic = null;
  234. print('Ingame music started: $selectedTrack (theme: $themeId)');
  235. } catch (e) {
  236. print('Failed to play ingame music: $e');
  237. }
  238. }
  239. Future<void> playBackgroundMusic() async {
  240. // Fallback method - defaults to menu music for compatibility
  241. await playMenuMusic();
  242. }
  243. Future<void> stopBackgroundMusic() async {
  244. if (!_isAudioSupported) return;
  245. try {
  246. await FlameAudio.bgm.stop();
  247. _currentMenuMusic = null;
  248. _currentIngameMusic = null;
  249. _isMenuMusic = false;
  250. } catch (e) {
  251. print('Failed to stop background music: $e');
  252. }
  253. }
  254. Future<void> pauseBackgroundMusic() async {
  255. if (!_isAudioSupported) return;
  256. try {
  257. FlameAudio.bgm.pause();
  258. } catch (e) {
  259. print('Failed to pause background music: $e');
  260. }
  261. }
  262. Future<void> resumeBackgroundMusic() async {
  263. if (!_musicEnabled || !_isAudioSupported) return;
  264. try {
  265. FlameAudio.bgm.resume();
  266. } catch (e) {
  267. print('Failed to resume background music: $e');
  268. }
  269. }
  270. void setSoundEnabled(bool enabled) {
  271. _soundEnabled = enabled;
  272. }
  273. void setMusicEnabled(bool enabled) {
  274. _musicEnabled = enabled;
  275. if (!enabled) {
  276. stopBackgroundMusic();
  277. } else {
  278. // Resume appropriate music based on context
  279. if (_isMenuMusic ||
  280. (_currentMenuMusic != null && _currentIngameMusic == null)) {
  281. playMenuMusic();
  282. } else {
  283. playIngameMusic();
  284. }
  285. }
  286. }
  287. void setBgmVolume(double volume) {
  288. _bgmVolume = volume;
  289. // Volume will be applied when music is next played
  290. }
  291. void setSfxVolume(double volume) {
  292. _sfxVolume = volume;
  293. // No effect with system audio
  294. }
  295. void setHapticEnabled(bool enabled) {
  296. _hapticEnabled = enabled;
  297. }
  298. Future<void> dispose() async {
  299. // Stop all audio immediately
  300. await stopBackgroundMusic();
  301. try {
  302. await FlameAudio.bgm.dispose();
  303. } catch (e) {
  304. print('Failed to dispose background player: $e');
  305. }
  306. try {
  307. await _popPool?.dispose();
  308. _popPool = null;
  309. } catch (e) {
  310. print('Failed to dispose popPool: $e');
  311. }
  312. try {
  313. await _popAltPool?.dispose();
  314. _popAltPool = null;
  315. } catch (e) {
  316. print('Failed to dispose popAltPool: $e');
  317. }
  318. // Clear all state
  319. _currentMenuMusic = null;
  320. _currentIngameMusic = null;
  321. _isMenuMusic = false;
  322. }
  323. // Utility method to get platform info for debugging
  324. String getPlatformInfo() {
  325. final audioType =
  326. _isAudioSupported ? 'Full Audio Support' : 'System Sounds Only';
  327. return 'Platform: ${Platform.operatingSystem}, '
  328. 'Audio: $audioType, '
  329. 'Vibration: $_isVibrationSupported';
  330. }
  331. }