在React Native中下载音频文件吗? [英] Download Audio file in react native?
问题描述
我正在尝试使用 rn-fetch-blob
下载音频文件"mp3".
I'm trying to download audio file "mp3" using rn-fetch-blob
.
所以我有不止一种情况:)
So I have more than one cases :)
当我尝试像这样向RNFetchBlob配置添加路径时
When I trying to add a path to RNFetchBlob config like this
const pathFile = RNFetchBlob.fs.dirs.MainBundleDir // Or .DocumentDir // Others is crashed my App 'Android';
回调"then"获得成功,因此它是日志
The callback "then" get success so it's Log
文件已保存到/data/user/0/com.music/files/RNFetchBlobTmp_1ueoigyb8hoscuuizzsue.mp3
但是当我尝试在真实设备中浏览此文件时,找不到它们,我也不知道为什么!
But when I try to explore this file in my real device I can't find them I don't know why!
那么Android中也有类似的问题吗?
So there's one faced same issue like this in Android?
startDownload = () => {
const {url} = this.state;
const pathFile = RNFetchBlob.fs.dirs.DocumentDir;
let date = new Date();
RNFetchBlob.config({
fileCache: true,
path:
pathFile +
'/me_' +
Math.floor(date.getTime() + date.getSeconds() / 2),
})
.fetch('GET', url)
.then(res => {
console.log('The file is save to ', res.path()); // It's log here but i can't see the file :\
})
.catch(err => console.log('err', err));
};
推荐答案
我首先通过请求许可来解决此问题,然后调用下载功能,
I solve this issue by request for permission firstly then call the download function,
但是实际上我不知道为什么他们告诉我在获得许可之前首先下载的文件:\
But actually I don't know why they tell me the file downloaded firstly before asking for permission :\
所以
requestToPermissions = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Music',
message:
'App needs access to your Files... ',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('startDownload...');
this.startDownload();
}
} catch (err) {
console.log(err);
}
};
startDownload = () => {
const {tunes, token, currentTrackIndex} = this.state;
let {url, name} = tunes[currentTrackIndex];
RNFetchBlob.config({
fileCache: true,
appendExt: 'mp3',
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
title: name,
path: RNFetchBlob.fs.dirs.DownloadDir + `${name}`, // Android platform
description: 'Downloading the file',
},
})
.fetch('GET', url)
.then(res => {
console.log('res', res);
console.log('The file is save to ', res.path());
});
};
这篇关于在React Native中下载音频文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!