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

会有一股神秘感。 提交于 2021-02-08 12:27:20

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/35473481/how-do-you-require-a-sound-file-in-react-native

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!