Maximum Duration of picked video using image picker plugin in Flutter

Viewed 1188

I'm using image picker plugin to pick videos from gallery in my flutter app. I want to set the maximum duration of the picked video to 30 seconds. The below code doesn't work even after setting the max duration. Is there any way to display an error or automatically trim the first 30secs if users pick a bigger video.

pickVideo(ImageSource src) async {
Navigator.pop(context);
final video = await ImagePicker().getVideo(
  source: src,
  maxDuration: Duration(seconds: 30),
);
1 Answers

I made a work around for this by throwing an error when a video longer than x seconds is selected. It looks as follows:

 Future<void> pickVideo() async {

try {
  final picker = ImagePicker();
  var pickedFile = await picker.pickVideo(source: ImageSource.gallery, maxDuration: Duration(seconds: maxSeconds));
  if (pickedFile == null) {
    return;
  }
  VideoPlayerController testLengthController = new VideoPlayerController.file(File(pickedFile.path));//Your file here
  await testLengthController.initialize();
  if (testLengthController.value.duration.inSeconds > 60) {
    pickedFile = null;
    throw('we only allow videos that are shorter than 1 minute!');

  } else {
    setState(() {
      videoFile = XFile(pickedFile.path);
      _startVideoPlayer();
    });
  }
  testLengthController.dispose();
} catch (e) {
  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Container(
            child: Text(e.toString()),
          ),
        );
      });
  return;
}

}

Related