12
votes

I'm using https://github.com/zmxv/react-native-sound to play sounds on my iOS (and Android) app, and I'm trying to include sound files through React Native's asset system, but when I call:

var sound = require('./sound.mp3');

I get the error:

Unable to resolve module ./sound.mp3 from [project]/index.ios.js: Invalid directory [project]/sound.mp3

I have my MP3 file in the correct (root) directory of my project, the exact same file path that the error is printing. I've tried putting it in other directories as well.

According to this thread, it sounds like sound files should be able to be packaged using require() as well?

Just doing a test, requiring an image works perfectly: var image = require('./image.png');

3
We can use webpack to require asset like mp3 file, could you check github.com/mjohnston/react-native-webpack-server - David Guan
@DavidGuan Thanks for the info! But based on this discussion, isn't it supposed to be built in to React Native?: github.com/facebook/react-native/issues/… - Dan Leveille
Have you looked at the example for loading sounds in the library you've said you're using? It doesn't look to me like you've imported the sound correctly github.com/zmxv/react-native-sound#basic-usage - Joseph Roque
@JosephRoque Yeah, I was trying to avoid that implementation (dropping each sound file into Xcode as well as an Android directory) -- I was going off of this ticket, which is suggesting that it could likely be done simply with require(): github.com/zmxv/react-native-sound/issues/14 - Dan Leveille

3 Answers

7
votes

What worked for me was simply using the app name as root:

import myMP3File from '<appname>/assets/mymp3.mp3';
const Sound = require('react-native-sound');
Sound.setCategory('Playback');

// Do whatever you like with it.
Sound(myMP3File, () => console.log('soundfile loaded!'));

Edit:

We now use rn-fetch-blob and the following solution to access local files:

import RNFetchBlob from 'rn-fetch-blob';
const { fs } = RNFetchBlob;
filePathIos = `${fs.dirs.MainBundleDir}/yourFolder/yourMp3.mp3`;
filePathAndroid = fs.asset('yourFolder/yourMp3.mp3');

The corresponding path can then be used to copy the file using fs.cp().

0
votes

The only thing that worked for us is to put the audio files we want to ship with the app in an assets directory and then have Xcode copy those files into the app bundle at build time. At that point, you can calculate the full path to the file using something like react-native-fs, and provide that to react-native-sound.

0
votes

I had the same error message with managed Expo when trying to play a sound.ogg. None of the trick I could find worked. In the end, what solved it was to convert the ogg file to mp3, which is supported by Expo.