react-nativereact-native-sound

play audio file without needing import/require


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?


Solution

  • 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.