How to record a video with Camera Plugin in flutter? - 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 ?

In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.

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;
}

Related

Flutter can't seem to find a Json file from relative path

I apologise in advance if this is a silly question, but I have created a file and stored it in my "assets" sub-directory, which is at the same level as my lib directory and my pubspec.yaml file. I've set the relative path to "assets/ExerData.json" in my code (see below).
When I run the code saved as a scratch.dart file as shown below, hitched up to a Galaxy Nexus API 29 emulator, it can only tell me "Can't find file!"
import 'dart:io';
import 'package:flutter/services.dart';
String filePath = "assets/ExerData.json";
void main() {
performTasks();
}
void performTasks() {
if (checkFileExists(filePath)) {
readFile(filePath);
} else {
print("Can't find file");
}
}
bool checkFileExists(path) {
bool result = File(path).existsSync();
print(result.toString());
return result;
}
Future<String> readFile(path) async {
return await rootBundle.loadString(filePath);
}
I populated my pubspec.yaml file with this entry:
assets:
- assets/ExerData.json
I expected it to find my file, read it using rootbundle.loadstring(path), and print out the resulting string to the console.
As I say, all it did was print "Can't find file".
I'd very much appreciate you help on this one!
Thanks in advance!
The rootBundle contains the resources that were packaged with the app when it was built. All files specified under assets: in your pubspec are packaged with the app. You can check if file exists by wrapping rootBundle.loadString() inside try{} catch(){} block.
Future<bool> fileExists(String path) async {
try {
await rootBundle.loadString(path);
} catch (_) {
return false;
}
return true;
}
or
Future<String?> loadFile(String path) async {
try {
return await rootBundle.loadString(path);
} catch (_) {
// File not found Exception
return null;
}
}
File is a dart class. It needs absolute or relative path of the file being read.
You can use File with path_provider to get the absolute path from the current File System.
For example on Android:
Future<void> getPath() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
print('PATH IS : $appDocPath');
}
prints
'/data/user/0/com.soliev.file_demo/app_flutter'
Use:
String data = await DefaultAssetBundle.of(context).loadString("assets/ExerData.json");
final jsonResult = jsonDecode(data);
Reference: How to load JSON assets into a Flutter App?
As it turns out, the program logic had not completed initializing the necessary binding.
I called the method WidgetsFlutterBinding.ensureInitialized() in the first line of the main class and everything started working as I expected.
Thanks to everyone who looked at my question!
Here's a similar question involving binding with XML files:
How to read XML files in flutter?

How can I save a file to a user specific directory flutter Desktop?

How can I allow the user to save a file to a specific folder in Flutter?
I have built a simple desktop app for Mac that returns a file from an API.
Currently, it saves the file to a caches directory.
try {
io.Directory saveDir = await getTemporaryDirectory();
String filePath = saveDir.path;
io.File returnedFile = new io.File('$filePath/$filename.xlsx');
await returnedFile.writeAsBytes(result.bodyBytes);
print(saveDir);
} catch (e) {
print(e);
}
I played around with my original code and that provided by #Pavel and managed to write my solution to saving files to a custom user-picked directory in this fashion.
The first part opens a file picker dialogue that returns a path to a directory.
The second part provides the path to the File class that then writes the file to that directory.
Hope this helps anyone trying to save files.
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Save Your File to desired location',
fileName: filename);
try {
io.File returnedFile = io.File('$outputFile');
await returnedFile.writeAsBytes(responsefile.bodyBytes);
} catch (e) {}
Use https://pub.dev/packages/file_picker
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Please select an output file:',
fileName: 'output-file.pdf',
);
if (outputFile == null) {
// User canceled the picker
}

Flutter: Is the sound really recorded in the designated file?

Recently I am using a package named flutter_sound v9.1.7. Here are some of the codes.
String _mPath = 'tau_file.mp4';
Codec _codec = Codec.aacMP4;
File? file;
FlutterSoundPlayer? _mPlayer = FlutterSoundPlayer();
FlutterSoundRecorder? _mRecorder = FlutterSoundRecorder();
void record() async {
_mRecorder!
.startRecorder(
toFile: _mPath,
codec: _codec,
audioSource: AudioSource.microphone,
)
.then((value) {});
setState(() {
recording = true;
});
}
I have succeeded in recording and playing audio, but when I finish recording and try to analyze the seeming audio file tau_file.mp4, such like get the length of the file, an error occurred:
Cannot retrieve length of file, path = 'tau_file.mp4' (OS Error: No such file or directory, errno = 2).
The analysis code is here:
file = File(_mPath);
print(file?.path);
print(file?.absolute);
print(file?.length.toString());
I tried to seek answer in source codes, but only found an interface... So is the audio really be written to the file tau_file.mp4? Or maybe the process of analysis is wrong?
This is the first time that I use flutter_sound. Thanks for your help.
void stopRecorder() async {
await _mRecorder!.stopRecorder().then((value) {
setState(() {
//var url = value;
recordedUrl = value;
debugPrint('path : -------- $recordedUrl');
_mplaybackReady = true;
});
});
}
This is your recorded files url, when you stop the record you can get it.
The document includes this code. It gives you //var url = value;. Then you can handle it. like var recordedFile = File(url);. it's not a temporary one. You can upload it somewhere or whatever you like.

How correcty evict image cache?

I'm trying to evict the image cache before take a picture, but it doesn't work and I cannot reupdate an image with the same name because it gives me cache error that the file already exists.
Directory pathCache;
String pathFile;
pathCache = await getTemporaryDirectory();
pathFile = pathCache.path+"/"+profilo+'.jpg';
print(pathFile);
try {
bool res =imageCache.evict(pathFile);
print("eviction result : $res");
imageCache.clear();
}
catch(e) {
print(e.toString());
}
try {
// Ensure that the camera is initialized.
await _initializeControllerFuture;
// Construct the path where the image should be saved using the
// pattern package.
final path = join(
// Store the picture in the temp directory.
// Find the temp directory using the `path_provider` plugin.
(await getTemporaryDirectory()).path,
profilo+'.jpg',
);
// Attempt to take a picture and log where it's been saved.
await _controller.takePicture(path);
What I'm missing?
Thanks
You are trying to clear only the cache, but the file still exists. You need to do:
Remove the old file (from the temporary directory)
Clear the cache
Take the new picture
File pictureFile = File(path);
if (pictureFile.existsSync()) {
pictureFile.deleteSync();
imageCache.clear();
}
...
await _controller.takePicture(path);

where do I need to store photo images in Flutter App?

I have an app that takes a photo.
I need that photo to be stored where all my assets/images/photos are.
So basically my question is :
a) how can I find the path where these assets are (on the phone)?
b) how can I add files to that same path?
Thanks
As per my knowledge you can not store image in assets package. Just because of when we build android/ios app after that assets folder is read only.
You need to store image in local mobile storage OR cloud OR catch memory
1) You can get storage path using :
Future<String> getStorageDirectory() async {
if (Platform.isAndroid) {
return (await getExternalStorageDirectory()).path; // OR return "/storage/emulated/0/Download";
} else {
return (await getApplicationDocumentsDirectory()).path;
}
}
2) Add image in path
createImage() async{
String dir= getStorageDirectory();
File directory = new File("$dir");
if (directory.exists() != true) {
directory.create();
}
File file = new File('$directory/image.jpeg');
var newFile = await file.writeAsBytes(/* image bytes*/);
await newFile.create();
}