我正在尝试播放和音频文件,但是我想动态加载文件,而不必在项目文件夹资产/音频上进行每个文件的导入。
当我使用导入时,下面的代码正在工作,但使用"文件"。
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()
});
});
};
如何在运行时提供文件名,以便我不需要导入每个音频文件?
您应该尝试这样做:
// 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());
});
通过Sound.main_bundle作为第二个参数。