audio_manager.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'package:audioplayers/audioplayers.dart';
  2. import 'package:vibration/vibration.dart';
  3. class AudioManager {
  4. static final AudioManager _instance = AudioManager._internal();
  5. final AudioPlayer _audioPlayer = AudioPlayer();
  6. bool _isPlaying = false;
  7. factory AudioManager() {
  8. return _instance;
  9. }
  10. AudioManager._internal();
  11. Future<void> playSound(String sound, double volume, bool loop) async {
  12. if (_isPlaying) {
  13. await stopSound();
  14. }
  15. // For this example, we're using dummy sound mapping
  16. // In a real app, you would have actual sound files
  17. String soundAsset;
  18. switch (sound) {
  19. case 'Dripping':
  20. soundAsset = 'assets/sounds/dripping.mp3';
  21. break;
  22. case 'Alarm':
  23. soundAsset = 'assets/sounds/alarm.mp3';
  24. break;
  25. case 'Bell':
  26. soundAsset = 'assets/sounds/bell.mp3';
  27. break;
  28. default:
  29. soundAsset = 'assets/sounds/dripping.mp3';
  30. }
  31. await _audioPlayer.setVolume(volume);
  32. await _audioPlayer.setReleaseMode(loop ? ReleaseMode.loop : ReleaseMode.release);
  33. await _audioPlayer.play(AssetSource(soundAsset));
  34. _isPlaying = true;
  35. }
  36. Future<void> stopSound() async {
  37. await _audioPlayer.stop();
  38. _isPlaying = false;
  39. }
  40. Future<void> triggerVibration() async {
  41. if (await Vibration.hasVibrator() ?? false) {
  42. Vibration.vibrate(pattern: [500, 1000, 500, 1000], repeat: 1);
  43. }
  44. }
  45. Future<void> stopVibration() async {
  46. if (await Vibration.hasVibrator() ?? false) {
  47. Vibration.cancel();
  48. }
  49. }
  50. Future<void> dispose() async {
  51. await stopSound();
  52. await stopVibration();
  53. await _audioPlayer.dispose();
  54. }
  55. }