2

I'm trying to play and audio file but I'd like to load the file dynamically without having to hardcode the import for each file on my project folder assets/audio.

The code below is working when I use the import, but not when I use the "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()
    });
  });
};

How can I provide the filename during runtime so that I don't need to import every audio file?

David Schumann
  • 13,380
  • 9
  • 75
  • 96
Artur Carvalho
  • 6,901
  • 10
  • 76
  • 105

1 Answers1

3

You should try to do this:

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

Pass Sound.MAIN_BUNDLE as the second param.

David Schumann
  • 13,380
  • 9
  • 75
  • 96
philipheinser
  • 311
  • 1
  • 6
  • 1
    It's also worth noting that in order for the files to be found using this method that they'll have to be added to the app bundle first. This info is included in the docs directly above your answer with instructions for iOS and Android: https://github.com/zmxv/react-native-sound#basic-usage – QMFNP Mar 02 '17 at 15:50
  • Thanks for the reply philiphenser, it's working. I tried that before but it was not working. I suppose that I forgot to rebuild xcode or restart the simulator. I also noticed that if we add a file in xcode, it creates a global var so I can put it in any folder after adding it. – Artur Carvalho Mar 02 '17 at 16:32