Detecting corrupt videos in Flutter Video Player - flutter

If I load a corrupt video into flutter video player using the following code the intialise future never completes nor is an error thrown... it just seems to hang.
videoController = VideoPlayerController.file(f)
..initialize().then((_) async {
setState(() {
});
}).catchError((error){
print(error);
}).whenComplete((){
print("ITS GONE IN THE whenComplete");
});
I have tried using the addListener to check if it has error but this also never is true.
e.g.
if (videoController.value.hasError) {
print(videoController.value.errorDescription);
const x = 1;
}
Is there anyway to tell whether a video has failed to load without using a timeout?
---- EDIT
Also I cannot use FFmpeg to test if the video is corrupt before using it.

Try to catch the error like this
try {
videoController = VideoPlayerController.file(f);
await videoController.initialize();
setState(() {});
} catch (e) {
print(error);
}

Related

How to resolve Lost Connection to Device (Flutter Image Picker)

I'm building an app that requires me to use the camera of the device. I have followed all the procedures to set it up via the Image Picker Documentation and I am still having issues.
Funny enough, it was working fine when I tested it last time but as I added new widgets to screen and tried testing again, the app crashed with very minimal error message which says:
Lost connection to device.
This is how I capture the image:
Future<void> _pickImage() async {
try {
bool isPermisionGranted = await _requestFilePermission();
if (!isPermisionGranted) {
showToast('Please give us access to your camera.');
return;
}
final image = await ImagePicker().pickImage(source: ImageSource.camera, imageQuality: 90);
if (image == null) return;
final tempImageFile = File(image.path);
setState(() {
_imageFile = tempImageFile;
});
if (!mounted) return;
Navigator.of(context).pushNamed(Routes.chi, arguments: {'image_file': _imageFile});
} on PlatformException catch (e) {
debugPrint('Failed to pick image: $e');
showToast('Failed to pick image');
}
}
Could this be a memory issue? And how can I resolve it?

Function expressions can't be named: then(

Im having issues with my code and since I'm new at using Flutter, I have no clue on how to fix it. I was trying to fix the http.get(string) and I kind of did, but now I'm having issues with then(()).
void submitForm(FeedbackForm feedbackForm) async {
try {
await http.get(Uri.parse(URL + feedbackForm.toParams()).then((response)) {
callback(convert.jsonDecode(response.body['status']));
});
} catch (e) {
print(e);
}
}
}
It seems you got a parenthesis missplaced:
await http.get(...).then((response) => callback(...))
The them allows you to use the result of the previous Future, as soon as it becomes available. If you find it confusing you can declare one variable at a time.
final response = await http.get(...);
// Check if response was as expected
await callback();

flutter_sound 8.4.2 startPlayer() exception

await _audioPlayer!.startPlayer(
fromURI: 'https://URL/TestFiles/sssssssss.acc',
codec: Codec.aacADTS,
);
} catch (e) {
print(e);
}
the exception is platform exceptio error unknown startplayer() error,null .
in the debug console I got these
FlutterSoundPlayer.log (package:flutter_sound/public/flutter_sound_player.dart:500:13
MethodChannelFlutterSoundPlayer.channelMethodCallHandler (package:flutter_sound_platform_interface/method_channel_flutter_sound_player.dart:161:19
I am using real android device
flutter doctor returns everything is good
this remote file works well in angular client
It's played Now I was missing that the file extension is aac not acc
so it should be
await _audioPlayer!.startPlayer(
fromURI: 'https://URL/TestFiles/sssssssss.aac',
);
} catch (e) {
print(e);
}
to play audios i use this library
audioplayers: ^0.19.1
declare this variable to access audio
String audioCorrect = "audio/access_granted.mp3";
String audioInCorrect = "audio/access_denied.mp3";
method for init player
void initPlayer() {
advancedPlayer = new AudioPlayer();
audioCache = new AudioCache(fixedPlayer: advancedPlayer);
}
call initPlayer in initState method
play the audio this way
audioCache.play(audioCorrect);

Lost connection to device in Flutter?

I'm facing a problem while using the plugins image_picker: "0.6.1+11" and
barcode_scan: "^1.0.0". Firstly I scan a barcode and then take a picture from the camera.
The problem is most of the times the android app restarts itself after taking image from the camera without any log. The log just prints "Lost connection to the device."
Here is the code:
Future scanCarton() async {
try {
String barcode = await BarcodeScanner.scan();
await getImage().then((imageFile){
if (imageFile != null){
Map<String,String>requestData = new Map<String,String>();
requestData["content"] = barcode;
requestData["type"] = "carton";
requestData["mode"] = "job";
if (widget.orderData.product_type.toLowerCase() == "batched"){
requestData["carton_id"] = "0";
}else{
requestData["carton_id"] = "${scannedCartonCount + 1}";
}
if(this.mounted){
setState(() {
_isLoading = true;
});
}else{
print("Gotcha 2");
}
upload(imageFile, UrlFile.UPLOAD_SCAN_IMAGE, "carton", requestData).then((value){
if(this.mounted){
setState(() {
_isLoading = false;
});
}else{
print("Gotcha 4");
}
incrementCartonCount();
if(widget.orderData.product_type.toLowerCase() == "batched"){
openNextCartonPopup();
}
});
}
});
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
print('The user did not grant the camera permission!');
} else {
print('Unknown error $e') ;
}
} on FormatException{
print( 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
print('Unknown error: $e');
}
}
You just need to configure to ask for permission beforehand.
For iOS, add the following keys to your Info.plist file, located at <project root>/ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describes why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
NSCameraUsageDescription - describes why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
NSMicrophoneUsageDescription - describes why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.
In the same way, you need to add permissions in Android.
Try your method with dispose()
#override
void dispose() {
[your method name].dispose();
super.dispose();
}
I got the same issue and found the solution. If you have TextField and imager picker in the same page, please make sure the textfield is unfocused (the cursor should be gone from you TextField) when you pick image.
Do something like FocusScope.of(context).requestFocus(new FocusNode()); in your pickImage method.

How can I limit video capturing via ImagePicker to 1 minutes maximum duration in Flutter?

I'm using ImagePicker to upload videos either from gallery or via capturing them from camera.
Problem is that I don't want the video to exceed 1 minute duration, when in gallery picking mode, I check the duration of selected video and show a message if video is longer than 1 minute.
How can I do something like retrica, open camera but with limit on video duration ?
use maxDuration provided by image_picker
final PickedFile videoFile = await picker.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 60),
);
I think you cant do this by ImagePicker because of this plugin capture video by phone default camera app and you haven't access to check and manage duration while capturing until the user stops capturing and return to your application
but if you use camera plugin you can do this because of this plugin capture video by your application and you have access to check video duration while user capture video
https://pub.dev/packages/camera
you can't controller it if you want to get this feature use Camera plugin
https://pub.dev/packages/camera
and use timer to stop recording
//Timer
timer = Timer.periodic(Duration(seconds: 60), (Timer t) {
_onStopButtonPressed();
timer.cancel();
});
});
//stop recording when click on the button
void _onStopButtonPressed() {
setState(() {
buttonColor = Colors.white;
});
_stopVideoRecording().then((_) {
if (mounted) setState(() {});
});
timer.cancel(); //when user close it manually
}
// stop funcation
Future<void> _stopVideoRecording() async {
if (!controller.value.isRecordingVideo) {
return null;
}
try {
await controller.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
also you can use video_player plugin to replay the video after recording
https://pub.dev/packages/video_player#-installing-tab-