audio_manager.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. String soundAsset;
  16. switch (sound) {
  17. case 'Dripping':
  18. soundAsset = 'assets/sounds/dripping.mp3';
  19. break;
  20. case 'Alarm':
  21. soundAsset = 'assets/sounds/alarm.mp3';
  22. break;
  23. case 'Bell':
  24. soundAsset = 'assets/sounds/bell.mp3';
  25. break;
  26. default:
  27. soundAsset = 'assets/sounds/dripping.mp3';
  28. }
  29. await _audioPlayer.setVolume(volume);
  30. await _audioPlayer
  31. .setReleaseMode(loop ? ReleaseMode.loop : ReleaseMode.release);
  32. await _audioPlayer.play(AssetSource(soundAsset));
  33. _isPlaying = true;
  34. }
  35. Future<void> stopSound() async {
  36. await _audioPlayer.stop();
  37. _isPlaying = false;
  38. }
  39. Future<void> triggerVibration() async {
  40. if (await Vibration.hasVibrator() ?? false) {
  41. // Vibrate continuously for 5 seconds
  42. Vibration.vibrate(duration: 1000);
  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. }