How to compress the video before uploading to database using react native

199 Views Asked by At

This is my whole page code to get video using react native image picker and then compress it using react-native compressor if anyone has done this functionality make sure to help and if possible you can message me on instagram @mujtaba._2 I have found 2 libraries one is react-native-compressor and react-native-video-processing . Issue that I am facing!

  1. Can't setup the library even after following the docs correctly
  2. Even I correctly placed the docs code in my android file the app doesn't build or even after building the video is not getting compressed

I think they should improve the docs or provide a better example

import React from 'react'
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
// import Video from 'react-native-video'
import { Video } from 'react-native-compressor';

const Addpost = ({ navigation }) => {
  const [cameraImg, setCameraImg] = React.useState(null)
  const [video, setVideo] = React.useState(null)
  console.log('this is video', video);
  const requestCameraPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: 'Camera Permission',
            message: 'App needs camera permission',
          },
        );
        // If CAMERA Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        return false;
      }
    } else return true;
  };

  const requestExternalWritePermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'External Storage Write Permission',
            message: 'App needs write permission',
          },
        );
        // If WRITE_EXTERNAL_STORAGE Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        console.log('Write permission err', err);
      }
      return false;
    } else return true;
  };
  const bufferConfig = {
    minBufferMs: 3000,
    maxBufferMs: 6000,
    bufferForPlaybackMs: 1500,
    bufferForPlaybackAfterRebufferMs: 3000,
  };
  const chooseFile = () => {
    let options = {
      mediaType: 'video',
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
    };
    launchImageLibrary(options, (response) => {
      //   console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        console.log('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        console.log('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        console.log(response.errorMessage);
        return;
      }
      setVideo(response);
    });
  };

  const captureImage = async () => {
    setCameraImg(null)
    setVideo(null)
    let options = {
      mediaType: 'video',
      maxWidth: 300,
      maxHeight: 550,
      allowsEditing: true,
      quality: 0,
      videoQuality: 'low',
      durationLimit: 10, //Video max duration in seconds
      saveToPhotos: false,
    };
    let isCameraPermitted = await requestCameraPermission();
    let isStoragePermitted = await requestExternalWritePermission();
    if (isCameraPermitted && isStoragePermitted) {
      launchCamera(options, (response) => {
        // console.log('Response = ', response);

        if (response.didCancel) {
          console.log('User cancelled camera picker');
          return;
        } else if (response.errorCode == 'camera_unavailable') {
          console.log('Camera not available on device');
          return;
        } else if (response.errorCode == 'permission') {
          console.log('Permission not satisfied');
          return;
        } else if (response.errorCode == 'others') {
          console.log(response.errorMessage);
          return;
        }
        // if(type=='video'){

        setVideo(response)
        // }
        // else
        // {setCameraImg(response)};
      });
    }
  };
  const gotoReels = () => {
    navigation.navigate('/Reels')
  }
  React.useEffect(() => {
    handleCompressVideo()
  }, [video])

  const handleCompressVideo = async () => {
    if (video) {
      try {
        const result = await Video.compress(video.uri, {
          compressionMethod: 'auto',
        }, (progress) => {
          console.log('Compression Progress:', progress);
          // Update progress if needed
        });

        console.log('Compressed Video:', result);
        // Handle the compressed video result as per your requirement
      } catch (error) {
        console.error('Video Compression Error:', error);
        // Handle any errors during compression
      }
    } else {
      console.warn('No video selected. Please select a video to compress.');
    }
  };
  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 1, alignItems: 'stretch' }}>
        <View style={styles.imgContainer}>
          {cameraImg && <Image source={{ uri: cameraImg.assets[0].uri }} alt='Img' style={styles.cameraImg} />}
          {/* {video &&
            <Video
              useBuffer={true}
              bufferConfig={bufferConfig}
              source={{ uri: video.assets[0].uri }}
              autoplay
              repeat={true}
              resizeMode={'cover'}
              style={{ width: '100%', height: '100%' }}
              customStyles={{
                wrapper: {
                  width: '100%',
                  height: '100%',
                  paddingBottom: 10,
                },
                video: {
                  width: '100%',
                  height: "100%",
                },
                controls: {
                  display: 'none',
                },
                seekBarBackground: {
                  backgroundColor: 'transparent',
                },
                seekBarProgress: {
                  backgroundColor: 'transparent',
                },
              }} />
          } */}
        </View>
        <View style={styles.options}>
          <Text style={styles.retake} onPress={captureImage}>{video ? 'Retake' : 'Take'} video</Text>
          <Text style={styles.retake} onPress={chooseFile}>Select From File</Text>
        </View>
        <View style={{ padding: 18 }}>
          <Pressable onPress={gotoReels} style={[styles.button, { marginBottom: 20, }]}
            disabled={!video}
          ><Text style={[styles.btnText,]}>Continue</Text></Pressable>
        </View>
      </View>
    </View>
  )
}

export default Addpost

const styles = StyleSheet.create({
  cameraImg: {
    width: '100%',
    height: "100%",
  },
  imgContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  options: {
    padding: 18,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  retake: {
    fontSize: 20,
    color: 'black',
    marginTop: 20,
  },
  button: {
    backgroundColor: 'black',
    padding: 14,
    width: '100%',
    borderRadius: 10,
    marginTop: 35,
  },
  btnText: {
    alignSelf: 'center',
    color: 'white',
    fontSize: 14
  }
})
0

There are 0 best solutions below