我正在使用 React Native 开发音频播放应用程序,但在使用文件/文件夹选择器获取文件时遇到问题。基本上,我将音频文件保存在设备上的某个文件夹中(而不是项目目录中)。我想使用https://www.npmjs.com/package/react-native-document-picker或使用 react-native-directory-picker (或类似的东西)的文件夹来获取文件,并获取包括 uri 在内的元数据, react-native-track-player,但文件选择器获取的 url 似乎不适用于轨道播放器。有没有更好的方法来解决这个问题?
这是我到目前为止尝试过的实现。请注意,我将文件保存在本地设备上的 Downloads 文件夹下,并且我尝试过传递 str、str2、str3 和 str4。每次,我都会从 reac-native-sound 记录错误:'failed to load the sound':
import DocumentPicker from 'react-native-document-picker';
var Sound = require('react-native-sound');
Sound.setCategory('Playback');
async SingleFilePicker() {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.audio],
});
this.setState({audioFile: res});
Alert.alert('You picked ' + res.name + ' with uri: ' + res.uri);
// Create audio object with name, artist, album, and length
// Display object
var str = 'content://';
var str2 = res.uri;
var str3 = str2.split('//').pop();
console.log(str3);
var str4 = 'file:///storage/emulated/0/Downloads/signofthecross_22_gaume_128kb.mp3';
var whoosh = new Sound(str4, Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound ' + str4, error);
return;
}
// loaded successfully
console.log(
'duration in seconds: ' +
whoosh.getDuration() +
'number of channels: ' +
whoosh.getNumberOfChannels(),
);
// 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) {
if (DocumentPicker.isCancel(err)) {
Alert.alert('Canceled Operations');
} else {
Alert.alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
}