'Flutter recording feature working on emulator but not on actual device

I am developing an app that can record and play sound. Everything works fine on my emulator. But when I try to run the app on my device, it always gives me this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'long android.os.storage.StorageVolume.getMaxFileSize()' on a null object reference

The way I implement the recording feature is to record the audio to a temporary file, and playback from it. This is the corresponding code, I am using flutter sound by the way:

String pathToSaveAudio = '';
class SoundRecorder {
  FlutterSoundRecorder? _audioRecorder;
  bool _isRecordingInitialised = false;
  bool get isRecording => _audioRecorder!.isRecording;

  // getters
  bool getInitState() {
    return _isRecordingInitialised;
  }

  FlutterSoundRecorder? getRecorder() {
    return _audioRecorder;
  }

  /// init recorder
  Future init() async {
    _audioRecorder = FlutterSoundRecorder();

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

    await _audioRecorder!.openRecorder();
    _isRecordingInitialised = true;

    var tempDir = await getTemporaryDirectory();
    pathToSaveAudio = '${tempDir.path}/audio.mp4';
  }

  /// dipose recorder
  void dispose() {
    _audioRecorder!.closeRecorder();
    _audioRecorder = null;
    _isRecordingInitialised = false;
  }

  /// start record
  Future _record() async {
    assert(_isRecordingInitialised);
    await _audioRecorder!
        .startRecorder(toFile: pathToSaveAudio, codec: Codec.aacMP4);
  }

  /// stop record
  Future _stop() async {
    if (!_isRecordingInitialised) return;
    await _audioRecorder!.stopRecorder();
  }

I think what I'm doing is record the sound and put it in the file in that temp directory. But appearently the app want to acces the file before I even start recording. At this point, I don't know what to do, please help me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source