你如何在 React Native 中 require() 一个声音文件? [英] How do you require() a sound file in React Native?

查看:61
本文介绍了你如何在 React Native 中 require() 一个声音文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://github.com/zmxv/react-native-sound 在我的 iOS(和 Android)应用程序上播放声音,我试图通过 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');

我收到错误:

无法从 [project]/index.ios.js 解析模块 ./sound.mp3:无效目录 [project]/sound.mp3

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

我的 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.

根据这个线程,听起来像是声音文件应该也可以使用 require() 打包吗?

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

只是做一个测试,需要一张图片完美运行:var image = require('./image.png');

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

推荐答案

对我有用的只是将应用程序名称用作 root:

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

我们现在使用 rn-fetch-blob 和访问本地文件的以下解决方案:

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

然后可以使用相应的路径使用fs.cp()复制文件.

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

这篇关于你如何在 React Native 中 require() 一个声音文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆