audio_manager.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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
  33. .setReleaseMode(loop ? ReleaseMode.loop : ReleaseMode.release);
  34. await _audioPlayer.play(AssetSource(soundAsset));
  35. _isPlaying = true;
  36. }
  37. Future<void> stopSound() async {
  38. await _audioPlayer.stop();
  39. _isPlaying = false;
  40. }
  41. Future<void> triggerVibration() async {
  42. if (await Vibration.hasVibrator() ?? false) {
  43. // Vibrate continuously for 5 seconds
  44. Vibration.vibrate(duration: 5000);
  45. }
  46. }
  47. Future<void> stopVibration() async {
  48. if (await Vibration.hasVibrator() ?? false) {
  49. Vibration.cancel();
  50. }
  51. }
  52. Future<void> dispose() async {
  53. await stopSound();
  54. await stopVibration();
  55. await _audioPlayer.dispose();
  56. }
  57. }