2

我正在尝试播放和音频文件,但我想动态加载文件,而不必对我的项目文件夹 assets/audio 中的每个文件的导入进行硬编码。

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

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

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

4

1 回答 1

3

你应该尝试这样做:

// 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 作为第二个参数传递。

于 2017-03-02T15:37:44.747 回答