Are there any react-native packages(npm) to compress videos? I want to compress the videos so that uploading these videos will take less time.
I am using Shobbak/react-native-compressor for a while now and it does seem to do the job.
Usage (per docs):
import { Video } from 'react-native-compressor';
const result = await Video.compress(
'file://path_of_file/BigBuckBunny.mp4',
{
compressionMethod: 'auto',
},
(progress) => {
if (backgroundMode) {
console.log('Compression Progress: ', progress);
} else {
setCompressingProgress(progress);
}
}
);
Related
I am building a mobile app by using EXPO.Now i am stucked in a img & pdf picker,i can't pick image and pdf in one single function or button. can anyone know any packages that enable pdf & image picker in one function.....
You can use expo document picker to pick multiple file types and images as following:
import * as DocumentPicker from 'expo-document-picker';
const picker = await DocumentPicker.getDocumentAsync({
type: "*/*",
multiple: true,
copyToCacheDirectory: true
});
Check the official expo docs DocumentPicker
If you wanna allow your user to select pdf then you can do this
async function openDocumentPicker() {
try {
const res = await DocumentPicker.getDocumentAsync({
type: "*/*",
copyToCacheDirectory: true,
multiple: false,
});
console.log(res)
var lastThree = res.name.substr(res.name.length - 3);
if(lastThree == 'pdf')
{
if(res.type == 'success')
{
//Do Something here
}
}
else
{
alert('Please select PDF File')
}
} catch (error) {
alert(error);
}
}
when uploading a video on, how to get its size.
I can set a limit to the duration but not the size.
I used this module
react-native-image-picker
this is the code used:
import ImagePicker from 'react-native-image-picker';
ImagePicker.showImagePicker(options, response => {
this.setState({ loading: false });
if (response.didCancel) {
console.log('User cancelled video picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
let path = '';
if (Platform.OS === 'android') {
path = response.path;
} else {
path = response.uri;
}
const videoExtentionPos = path.lastIndexOf('.');
const videoExtention = path.substring(videoExtentionPos + 1);
this.setState({
fields: {
...fields,
posts_video: {
uri: response.uri,
type: `video/${videoExtention}`,
name: `video.${videoExtention}`
}
}
});
}
});
There is not direct way to get it done. You will need to check the file size and show alert if it is not what you expect.
You can get the file size with rn-fetch-blob package.
You can use react-native-fs as well.
I am trying to learn react native and how to download files to the device. I know you can do this with react native file system but that does not support authentication which I need. React native fetch blob does support this.
For education purposes, I want to have the code from the first answer to this question recreated in react native fetch blob instead of react native file system.
I someone could write sutch an examlple form me I would be super tankfull.
Question: Downloading data files with React Native for offline use
Try this, it's work fine on Android:
export const download = (url, name) => {
const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: PictureDir + name,
description: t('downloading_file')
}
};
config(options)
.fetch('GET', url)
.then(res => {
if (res.data) {
alert(t('download_success'));
} else {
alert(t('download_failed'));
}
});
};
downloadImage(){
var date = new Date();
var url = "http://debasish.com/image.jpg";
var ext = this.getExtention(url);
ext = "."+ext[0];
const { config, fs } = RNFetchBlob ;
let PictureDir = fs.dirs.PictureDir
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : true,
path: PictureDir + "/image_"+Math.floor(date.getTime()
+ date.getSeconds() / 2)+ext,
description : 'Image'
}
}
config(options).fetch('GET', url).then((res) => {
Alert.alert("Download Success !");
});
}
getExtention(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) :
undefined;
}
I have audio files hosted on a server that I'd like my app to access after authenticating. Users send a GET request which includes an authentication token, and the server returns the binary audio data.
As far as I can see there is no way to save this 'blob' as an audio file to the filesystem. The current implementation of fetch in react-native doesn't support blobs: link
... and the ideally-suited react-native-fetch-blob library isn't supported in expo either: link
Additionally I can see no way of streaming the audio file from the server. The included audio library with expo allows streaming of audio from a url (e.g. http://example.com/myaudio.mp3) however I can't see any way to attach an authorisation header to the request (e.g. "Authorization": "Bearer [my-token]").
Is there a way of achieving this, either by downloading and saving the audio blob, or streaming from a url with an authorisation header included in the request? I could detach my project from Expo but I'd like to leave that as a last-resort.
Yes, it is. You need to use the Audio module exposed by expo to do it. Below are the steps that you have to follow to load and play an audio file from a given URL. I've also copied over the code for my component that is doing the same for me.
Load Audio module exposed by expo
import { Audio } from 'expo'
Create a new sound Object from it
soundObject = new Audio.Sound()
Asynchronously load your file
await this.soundObject.loadAsync({ uri: this.props.source })
Once loaded play the loaded file using
this.soundObject.playAsync()
Below is a simple component that I wrote for doing it -
import React, { Component } from 'react';
import { View, TouchableNativeFeedback } from 'react-native';
import { Audio } from 'expo';
class AudioPlayer extends Component {
constructor(props) {
super(props);
this.state = { isPlaying: false };
this.loadAudio = this.loadAudio.bind(this);
this.toggleAudioPlayback = this.toggleAudioPlayback.bind(this);
}
componentDidMount() {
this.loadAudio();
}
componentWillUnmount() {
this.soundObject.stopAsync();
}
async loadAudio() {
this.soundObject = new Audio.Sound();
try {
await this.soundObject.loadAsync({ uri: this.props.source /* url for your audio file */ });
} catch (e) {
console.log('ERROR Loading Audio', e);
}
}
toggleAudioPlayback() {
this.setState({
isPlaying: !this.state.isPlaying,
}, () => (this.state.isPlaying
? this.soundObject.playAsync()
: this.soundObject.stopAsync()));
}
render() {
return (
<TouchableNativeFeedback onPress={this.toggleAudioPlayback}>
<View style={this.props.style}>
{this.props.children}
</View>
</TouchableNativeFeedback>
);
}
}
export default AudioPlayer;
i figured it out. I should've load the sound in componentdidmount using async. In case someone met this problem
componentDidMount() {
this.loadAudio();
}
//async function to load the audio
async loadAudio() {
const { navigation } = this.props;
const id = navigation.getParam("id");
this.sound = new Audio.Sound();
for (let i = 0; i < soundArray.length; i++) {
if (soundArray[i].id === id) {
this.currentSound = soundArray[i];
console.log(this.currentSound);
break;
}
}
try {
await this.sound.loadAsync({
uri: this.currentSound.sound /* url for your audio file */
});
await this.sound.setOnPlaybackStatusUpdate(
this._updateScreenForSoundStatus
);
} catch (e) {
console.log("ERROR Loading Audio", e);
}
}
I searched a lot about the way to capture image by phone camera, then I can crop it, and finally I want to upload croped image on firebase…
Is that possible for ionic 2 ? Or no way to did these three steps togather ?
You can capture an image using the phone camera and crop it and upload to the server. There are two options as follows.
https://github.com/jeduan/cordova-plugin-crop
https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin
Option 1:
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { Camera, Crop } from 'ionic-native';
#Injectable()
export class CameraService {
public options: any = {
allowEdit: true,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
mediaType: Camera.MediaType.ALLMEDIA,
destinationType: Camera.DestinationType.FILE_URI
}
constructor(public platform: Platform) {}
// Return a promise to catch errors while loading image
getMedia(): Promise<any> {
// Get Image from ionic-native's built in camera plugin
return Camera.getPicture(this.options)
.then((fileUri) => {
// Crop Image, on android this returns something like, '/storage/emulated/0/Android/...'
// Only giving an android example as ionic-native camera has built in cropping ability
if (this.platform.is('ios')) {
return fileUri
} else if (this.platform.is('android')) {
// Modify fileUri format, may not always be necessary
fileUri = 'file://' + fileUri;
/* Using cordova-plugin-crop starts here */
return Crop.crop(fileUri, { quality: 100 });
}
})
.then((path) => {
// path looks like 'file:///storage/emulated/0/Android/data/com.foo.bar/cache/1477008080626-cropped.jpg?1477008106566'
console.log('Cropped Image Path!: ' + path);
return path;
})
}
}