Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you require() a sound file in React Native?

Tags:

react-native

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');

like image 372
Dan Leveille Avatar asked Feb 18 '16 05:02

Dan Leveille


People also ask

How do I play sound files in react native?

To play the file, we can use the play method from Sound , as follows: ding. play(success => { if (success) { console. log('successfully finished playing'); } else { console.

How do I save an audio file in react native?

Record Audio in React NativeFirstly, we start by defining an audio file name and extension. Secondly, we define the audio format preference. Lastly, we start to record audio and add a record time to the state. Here, we can see that the timer starts as we tap on the RECORD button.


1 Answers

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().

like image 69
David Schumann Avatar answered Oct 17 '22 01:10

David Schumann