Untitled
import 'dart:developer'; import 'dart:io'; import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:record/record.dart'; import 'package:path_provider/path_provider.dart'; import 'dart:async'; class AudioNotifier extends ChangeNotifier { bool _isRecording = false; bool _isPaused = false; Duration _recordDuration = Duration.zero; Timer? _timer; String? filePath; final AudioRecorder _record = AudioRecorder(); final AudioPlayer _player = AudioPlayer(); bool get isRecording => _isRecording; bool get isPaused => _isPaused; Duration get recordDuration => _recordDuration; // Helper method to format the duration as MM:SS String get formattedRecordDuration { final minutes = _recordDuration.inMinutes.remainder(60).toString().padLeft(2, '0'); final seconds = _recordDuration.inSeconds.remainder(60).toString().padLeft(2, '0'); return '$minutes:$seconds'; } void setIsRecording(bool newValue) { log(newValue.toString()); _isRecording = newValue; notifyListeners(); } void setIsPaused(bool newValue) { log(newValue.toString()); _isPaused = newValue; notifyListeners(); } void _startTimer() { _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) { if (!_isPaused) { _recordDuration = Duration(seconds: _recordDuration.inSeconds + 1); notifyListeners(); } }); } void _stopTimer() { _timer?.cancel(); } Future<void> startRecording() async { if (await _record.hasPermission()) { final directory = await getApplicationDocumentsDirectory(); filePath = '${directory.path}/audio_recording.m4a'; await _record.start( const RecordConfig(), path: filePath!, ); _startTimer(); setIsRecording(true); setIsPaused(false); } } Future<void> pauseRecording() async { if (_isRecording && !_isPaused) { await _record.pause(); setIsPaused(true); } } Future<void> resumeRecording() async { if (_isRecording && _isPaused) { await _record.resume(); setIsPaused(false); } } Future<void> stopRecording() async { await _record.stop(); _stopTimer(); setIsRecording(false); setIsPaused(false); if (filePath != null) { log('Recording saved at: $filePath'); } } Future<void> playAudio() async { if (filePath != null && await File(filePath!).exists()) { await _player.play(DeviceFileSource(filePath!)); } else { log('No file found or file does not exist'); } } // Method to reset all values in the notifier void reset() { _stopTimer(); _isRecording = false; _isPaused = false; _recordDuration = Duration.zero; filePath = null; } @override void dispose() { _stopTimer(); _player.dispose(); super.dispose(); } }
Leave a Comment