Untitled

mail@pastecode.io avatar
unknown
dart
11 days ago
2.6 kB
1
Indexable
Never
 final FlutterSoundPlayer _player = FlutterSoundPlayer();
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
  bool _isPlaying = false;
  bool _isRecording = false;
  String _recordedFilePath = '';
  Duration _recordDuration = Duration.zero;

  AudioNotifier() {
    _init();
  }

  bool get isPlaying => _isPlaying;
  bool get isRecording => _isRecording;
  String get recordedFilePath => _recordedFilePath;
  Duration get recordDuration => _recordDuration;

  Future<void> _init() async {
    await _player.openPlayer();

    // Request microphone permission
    var status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      throw Exception('Microphone permission not granted');
    }

    await _recorder.openRecorder();
    _recorder.onProgress?.listen((event) {
      _recordDuration = event.duration;
      notifyListeners();
    });
  }

  Future<void> startRecording() async {
    if (_isRecording) {
      _recordedFilePath = 'recorded_audio.aac';
      //_recordDuration = Duration.zero;
      await _recorder.startRecorder(
        toFile: _recordedFilePath,
        codec: Codec.aacADTS,
      );

      log(_recordDuration.toString());
      setIsRecording(true);
      notifyListeners();
    }
  }

  Future<void> pauseRecording() async {
    if (_isRecording) {
      await _recorder.pauseRecorder();
      setIsRecording(false);
      notifyListeners();
    }
  }

  Future<void> resumeRecording() async {
    if (!_isRecording && _recorder.isPaused) {
      await _recorder.resumeRecorder();
      setIsRecording(true);
      notifyListeners();
    }
  }

  Future<void> stopRecording() async {
    if (_isRecording || _recorder.isPaused) {
      await _recorder.stopRecorder();
      setIsRecording(false);
      notifyListeners();
    }
  }

  Future<void> playRecording() async {
    if (_recordedFilePath.isNotEmpty) {
      await _player.startPlayer(
        fromURI: _recordedFilePath,
        codec: Codec.aacADTS,
        whenFinished: () {
          _isPlaying = false;
          notifyListeners();
        },
      );
      _isPlaying = true;
      notifyListeners();
    }
  }

  Future<void> pausePlayer() async {
    if (_isPlaying) {
      await _player.pausePlayer();
      _isPlaying = false;
      notifyListeners();
    }
  }

  Future<void> stopPlayer() async {
    if (_isPlaying) {
      await _player.stopPlayer();
      _isPlaying = false;
      notifyListeners();
    }
  }

  @override
  void dispose() {
    _player.closePlayer();
    _recorder.closeRecorder();
    setIsRecording(false);
    super.dispose();
  }
Leave a Comment