无需 import/require 即可播放音频文件

play audio file without needing import/require

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

下面的代码在我使用导入时有效,但在我使用 "file" 时无效。

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