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. // 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. Vibration.vibrate(pattern: [500, 1000, 500, 1000], repeat: 1);
  44. }
  45. }
  46. Future<void> stopVibration() async {
  47. if (await Vibration.hasVibrator() ?? false) {
  48. Vibration.cancel();
  49. }
  50. }
  51. Future<void> dispose() async {
  52. await stopSound();
  53. await stopVibration();
  54. await _audioPlayer.dispose();
  55. }
  56. }