Воспроизвести аудио файл без необходимости импорта / требуют

Я пытаюсь воспроизвести и аудио файл, но я хотел бы загрузить файл динамически, без необходимости жестко кодировать импорт для каждого файла в папке проекта / аудио / аудио.

Код ниже работает, когда я использую импорт, но не когда я использую "файл".

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 ответ

Решение

Вы должны попытаться сделать это:

// 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 в качестве второго параметра.

Другие вопросы по тегам