I'm using react-native-fetch-blob to download the File .
The File is residing at RNFS.DocumentDirectoryPath + fileExtension;
eq: RNFS.DocumentDirectoryPath /myMusic.mp3;
the downloaded file is located at
/data/user/0/com.myproject/files/myMusic.mp3
and As per react-native-sound it is asking to place the files under raw folder.
when I follow the below code using react-native-fs, Its Playing !!!!
downloadFileAndPlay()
{
console.log('Download');
const downloadDest = RNFS.DocumentDirectoryPath + '/sample.mp3';
const ret = RNFS.downloadFile(
{
fromUrl: 'http://www.julien-gustin.be/files/sample.mp3',
toFile: downloadDest
}
);
ret.promise.then(res => {
console.log(res);
// Load the sound file 'whoosh.mp3' from the app bundle
// See notes below about preloading sounds within initialization code below.
console.log(downloadDest);
var whoosh = new Sound(downloadDest, '', (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// loaded successfully
console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());
if(whoosh.isLoaded()){
console.log('LOADED');
}else{
console.log('NOT LOADED');
}
// Play the sound with an onEnd callback
whoosh.play((success) => {
if (success) {
console.log('successfully finished playing');
} else {
console.log('playback failed due to audio decoding errors');
}
});
});
}).catch(err => {
console.log(err);
});
}
in both places I'am using the same Directory path . But in our case its not playing ..
How can I retrieve the downloaded file and play While I am calling this file from another component?
This works for me, but with react-native-video
<Video
source={{ uri: "file://" + RNFS.DocumentDirectoryPath + "/Claymore-OP01-NCBD.mp4" }} />
so basically, add the schema before the path:
file://somepath.mp3
Related
im using react-native-document-picker but have problem on IOS. i cant open photo files. is there anyone ever face this issue ? and how to resolve this. please advise. below here is my code :
handleSuffixIcon={async () => {
try {
const pickerResult = await DocumentPicker.pickSingle({
presentationStyle: 'fullScreen',
copyTo: 'documentDirectory',
type:
Platform.OS === 'ios'
? ['public.jpeg', 'public.png', 'com.adobe.pdf']
: ['image/png', 'image/jpeg', 'application/pdf'],
});
if (pickerResult?.size <= 5000000) {
setSizeMsg('');
setUri(pickerResult?.fileCopyUri);
setDocument(pickerResult?.name);
setSize(pickerResult?.size);
setType(pickerResult?.type);
} else {
setUri('');
setDocument('');
setType('');
setSizeMsg({ error: trans(locale, lang, 'sizeToLarge') });
}
} catch (e) {
// eslint-disable-next-line no-console
console.log('error : ', e);
}
}}
my goals is to add more option like photo files. because in my project i have to send an image which is PNG/JPEG but also a document. and because i cant access my photo files. it really messy :(
I have implemented a document picker in my react native application and it is working fine for iOS. However in Android, I am having a weird issue
When I open the document picker and the navigation takes to the file explorer (Downloads section) in Android phone, though I am able to select the pdf file but, when it comes to the application back, it stuck to the page and the file is not there. I have attached the screenshot Same behaviour when the file explorer takes to the recent files. Only when from the recent files, I select the google drive and try to select the pdf from there, it works as expected and I can see the file in my application and the app do not stuck.
Here is what I have written for the pdf document picker
selectPDF = async ()=>{
var imageList = [...this.state.files];
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.pdf],
});
for (const res of results) {
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
const fileName = res.uri.replace("file://","");
let data1 = ''
RnFetchBlob.fs.readStream(
fileName,
'base64',
4095
)
.then((ifstream)=>{
//let data1 = ''
ifstream.open()
ifstream.onData((data)=>{
data1 += data;
})
ifstream.onEnd(() => {
let base64 = data1
imageList.push({
imageName:res.name,
image:base64,
mime:res.type,
size:res.size
})
this.setState({
...this.state,
openCamera:false,
lastFileName:imageList[imageList.length - 1].imageName,
files:imageList
})
})
})
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
this.closeModal();
} else {
throw err;
}
}
}
Can anyone throw some light as to what I may be missing. Is some configuration needs to be set on device level or any other thing.
you can use something like this,
const [file, setFile] = useState(null);
const selectFile = async () => {
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.allFiles],
});
setFile(results);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
alert('Canceled');
} else {
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
now you can call file in your function
and to use it you can do like this
<TouchableOpacity
activeOpacity={0.5}
onPress={selectFile}>
<Text>Select File</Text>
</TouchableOpacity>
Part 2 of a earlier question on uploading camera images from my iOS to my S3 account
I have an S3 bucket with the default ACL and policy. I finally got my nativescript-aws-sdk to build and but I am struggling to see what I need to do to actually use it..
I have this:
app.js:
import { S3 } from "nativescript-aws-sdk/s3";
S3.init({ endPoint: '/images/person', accessKey: config.AWS_ACCESS_KEY, secretKey: config.AWS_SECRET_KEY, type: 'static' });
person.vue:
<script>
import { takePicture, requestPermissions } from "nativescript-camera";
import config from "../../config.json";
import { S3 } from 'nativescript-aws-sdk/s3';
const s3 = new S3();
...
requestPermissions()
.then( () => {
takePicture({ width: that.width, height: that.height, keepAspectRatio: that.keepAspectRatio, saveToGallery: that.saveToGallery, allowsEditing: that.allowsEditing })
.then((imageAsset) => {
that.cameraImage = imageAsset;
...
}
uploadPicture() {
console.log('uploadPicture called..');
var currentDate = new Date();
var timestamp = currentDate.getTime();
let fileName = this.person.lastName+ timestamp + '.jpg';
console.log('working with image file: ' + fileName);
console.log('working with image : ' + that.cameraImage);
const imageUploaderId = s3.createUpload({
file: that.cameraImage,
bucketName: config.AWS_BUCKET_NAME,
key: `ns_${isIOS ? 'ios' : 'android'}`+fileName,
acl: 'public-read',
completed: (error, success) => {
if (error) {
console.log(`S3 Download Failed :-> ${error.message}`);
}
if (success) {
console.log(`S3 Download Complete :-> ${success.path}`);
}
},
progress: progress => {
console.log(`Progress : ${progress.value}`);
}
}).catch((err) => {
console.error("createUpload() caught error: " + JSON.stringify(err));
});
console.log('working with iimageUploaderId: ' + imageUploaderId);
// s3.pause(imageUploaderId);
// s3.resume(imageUploaderId);
// s3.cancel(imageUploaderId);
}
However, I feel like I must be doing something wrong because the createUpload doesn't seem to complete as my error logs are:
CONSOLE LOG file:///app/components/Person.vue:304:0: 'uploadPicture called..'
CONSOLE LOG file:///app/components/Person.vue:308:0: 'working with image file: Flintstone1585334134497.jpg'
So am I missing something?
I am developing a React Native project. What I am trying to do now is that I am downloading and saving the downloaded file to the device. I am using this package, https://www.npmjs.com/package/rn-fetch-blob for downloading the file.
This is my code
RNFetchBlob.config({
fileCache: true,
})
.fetch('GET', 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968', {
})
.then((res) => {
Alert.alert(res.path());
})
After download, res.path returns the path like this.
I am trying to convert it to the URI to be displayed using the Image component. I tried binding the following state object to the Image component.
{
uri: res.path()
}
It did not work. That is why as a next attempt, I am trying to convert the path into URI and display the uri. How can I do that?
Try providing the path of the file where you want to download it,
const directoryFile = RNFS.ExternalStorageDirectoryPath + "/FolderName/";
RNFS.mkdir(directoryFile);
const urlDownload = input.url;
let fileName;
fileName = "filename.zip";
let dirs = directoryFile + fileName;
RNFetchBlob.config({
// response data will be saved to this path if it has access right.
path: dirs
}).fetch("GET", urlDownload, {
//some headers ..
})
.then(res => {
console.log("The file saved to ", res.path());
//RNFS.moveFile(dirs, directoryFile + fileName); // -> uncomment this line if it still does not store at your desired path
alert("File Downloaded At Folder");
})
.catch(err => {
console.log("Error: " + err);
});
I'm trying to play and audio file but I'd like to load the file dynamically without having to hardcode the import for each file on my project folder assets/audio.
The code below is working when I use the import, but not when I use the "file".
const Sound = require('react-native-sound');
import t1 from './assets/audio/t1.mp3';
import t2 from './assets/audio/t2.mp3';
Sound.setCategory('Playback', true); // true = mixWithOthers
export const playSound = () => {
const file = './assets/audio/t1.mp3';
// const s = new Sound(file, (error) => { // does not work
const s = new Sound(t1, (error) => { // works
if (error) {
console.log('error', error);
return;
}
s.play(() => {
s.release()
});
});
};
How can I provide the filename during runtime so that I don't need to import every audio file?
You should try to do this:
// Load the sound file 'whoosh.mp3' from the app bundle
// See notes below about preloading sounds within initialization code below.
var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// loaded successfully
console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());
});
Pass Sound.MAIN_BUNDLE as the second param.