2017-03-02 86 views
1

我试图播放和音频文件,但我想动态加载文件,而不必硬编码我的项目文件夹资产/音频上的每个文件的导入。播放音频文件不需要导入/需要

以下代码在使用导入时正常工作,但在使用“文件”时不起作用。

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() 
    }); 
    }); 
}; 

如何在运行时提供文件名以便我不需要导入每个音频文件?

回答

2

你应该尽量做到这一点:

// 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作为第二PARAM。

+1

还值得注意的是,为了使用此方法找到文件,必须先将它们添加到应用程序包中。此信息包含在您的答案正上方的文档中,其中包含针对iOS和Android的说明:https://github.com/zmxv/react-native-sound#basic-usage – QMFNP

+0

感谢philiphenser的回复,它正在工作。我曾尝试过,但它不工作。我想我忘了重建xcode或重启模拟器。我还注意到,如果我们在xcode中添加一个文件,它会创建一个全局变量,因此我可以在添加它后将它放入任何文件夹中。 –