I am working on an audio playing app using React Native, but I'm having trouble fetching files using a file/folder picker. Basically, I have audio files saved in a certain folder on my device (not in the project directory). I want to fetch files using https://www.npmjs.com/package/react-native-document-picker or folders using react-native-directory-picker (or something like these), and fetch the metadata including uri, to react-native-track-player, but the url fetched by the file picker doesn't seem to work with the track player. Is there a better way to go about this?
Here's the implementation I've tried so far. Note, I have the file saved under the Downloads folder on my local device, and I've tried passing str, str2, str3, and str4. Each time, I get the error logged from 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;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…