无需导入/要求播放音频文件

时间:2017-03-02 13:22:06

标签: react-native react-native-sound

我正在尝试播放和音频文件,但我想动态加载文件,而无需对项目文件夹资产/音频上的每个文件进行硬编码。

以下代码在我使用导入时有效,但在使用“文件”时则无效。

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

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

1 个答案:

答案 0 :(得分: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作为第二个参数传递。