Flutter – How to save and play a recorded audio file?

Issue

I, for the life of me, can’t figure this out. All I am trying to do is record an audio (as in a sound/voice recorder) and later be able to play it.

Recorder class:

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

//String _pathToAudio = '/sdcard/myAudio.aac';
String _fileName = 'myAudio.aac';
String _path = "/storage/emulated/0";

class Recorder {
  FlutterSoundRecorder? _recorder;
  bool _isRecorderInitialized = false;
  bool get isRecording => _recorder!.isRecording;

  Future init() async {
    _recorder = FlutterSoundRecorder();
    //final directory = "/sdcard/downloads/";
    //Directory? extStorageDir = await getExternalStorageDirectory();
    //String _path = directory.path;

    final status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      throw RecordingPermissionException('Recording permission required.');
    }

    await _recorder!.openAudioSession();
    _isRecorderInitialized = true;
  }

  void _writeFileToStorage() async {
    File audiofile = File('$_path/$_fileName');
    Uint8List bytes = await audiofile.readAsBytes();
    audiofile.writeAsBytes(bytes);
  }

  void dispose() {
    _recorder!.closeAudioSession();
    _recorder = null;
    _isRecorderInitialized = false;
  }

  Future record() async {
    if (!_isRecorderInitialized) {
      return;
    }
    print('recording....');
    await _recorder!.startRecorder(
      toFile: '$_fileName',
      //codec: Codec.aacMP4,
    );
  }

  Future stop() async {
    if (!_isRecorderInitialized) {
      return;
    }
    await _recorder!.stopRecorder();
    _writeFileToStorage();
    print('stopped....');
  }

  Future toggleRecording() async {
    if (_recorder!.isStopped) {
      await record();
    } else {
      await stop();
    }
  }
}

Currently the error I am getting is "Cannot open file, path = ‘/storage/emulated/0/myAudio.aac’ (OS Error: No such file or directory, errno = 2)".

I am using flutter_sound

Solution

String _fileName = 'Recording_';
String _fileExtension = '.aac';
String _directoryPath = '/storage/emulated/0/SoundRecorder';

This is what I have currently and it’s working.

void _createFile() async {
  var _completeFileName = await generateFileName();
  File(_directoryPath + '/' + _completeFileName)
      .create(recursive: true)
      .then((File file) async {
    //write to file
    Uint8List bytes = await file.readAsBytes();
    file.writeAsBytes(bytes);
    print(file.path);
  });
}

void _createDirectory() async {
  bool isDirectoryCreated = await Directory(_directoryPath).exists();
  if (!isDirectoryCreated) {
    Directory(_directoryPath).create()
        // The created directory is returned as a Future.
        .then((Directory directory) {
      print(directory.path);
    });
  }
}

void _writeFileToStorage() async {
  _createDirectory();
  _createFile();
}

Answered By – who-aditya-nawandar

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *