Search code examples
fluttercameraandroid-cameravideo-recording

How to record a video with Camera Plugin in flutter?


I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :

FlatButton(
     onPressed: () => {
            !isRecording
                ? {
                   setState(() {
                   isRecording = true;
                  }),
                  cameraController.prepareForVideoRecording(),
                  cameraController.startVideoRecording('assets/Videos/test.mp4')
                }
               : cameraController.stopVideoRecording(),
              },
              ............

but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)). I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?


Solution

  • You are trying to save a video in your assets folder which is not possible ,

    What you need to do is to save to device locally either common folders like downloads or app directory.

    Here is an example of how to go about it

    dependencies:
      path_provider:
    

    Flutter plugin for getting commonly used locations on host platform file systems, such as the temp and app data directories.

    We will be saving the video to app directory.

    We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider

     Future<String> _startVideoRecording() async {
        
          if (!controller.value.isInitialized) {      
        
            return null;
        
          }  
        
          // Do nothing if a recording is on progress
        
          if (controller.value.isRecordingVideo) {
        
            return null;
        
          }
      //get storage path
        
          final Directory appDirectory = await getApplicationDocumentsDirectory();
        
          final String videoDirectory = '${appDirectory.path}/Videos';
        
          await Directory(videoDirectory).create(recursive: true);
        
          final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
        
          final String filePath = '$videoDirectory/${currentTime}.mp4';
        
      
        
          try {
        
            await controller.startVideoRecording(filePath);
        
            videoPath = filePath;
        
          } on CameraException catch (e) {
        
            _showCameraException(e);
        
            return null;
        
          }
        
      
        //gives you path of where the video was stored
          return filePath;
        
        }