资产音频文件无法在 Expo 中播放

Ash*_*hta 2 reactjs react-native expo

import AlphService from './AlphService';

export default class MyClass extends React.Component {
 alphService;
 constructor(props) {
  super(props);
  alphService = new AlphService();
  this.state = alphService.getState();
 }
 componentWillMount() {
    this.play(this.state.sound);
  }

  play(source) {
   console.log(source);
   Audio.setIsEnabledAsync(true);
   const sound = new Audio.Sound();
   const play_sound = (async () => {
    await sound.loadAsync(require(source)); //Error Here
    await sound.playAsync();
   })();
  }
}
Run Code Online (Sandbox Code Playgroud)

阿尔夫服务.js

export default class alphService {
 stateObj = {
  sound: ""
 };
 getState(){
  this.stateObj.sound = "../assets/sounds/c.mp3"; 
  return this.stateObj;
 }
}
Run Code Online (Sandbox Code Playgroud)

错误:components/Alphabet.js:第 51 行的调用无效:需要(来源)

并尝试require(soundPathVar)getState()方法返回对象并从 中删除 required play(),然后出现相同的错误。

我是 react-native 的初学者,我想尝试创建一个动态声音文件路径。所以如果我做错了,你能帮助我吗?预先感谢。

mAh*_*FeR 5

我在尝试require动态图像时遇到了这个问题,结果require只接受特定来源甚至require("SOURCE/" + "something.png")不起作用,它应该是require("SOURCE/something.png"). 尝试这个:

export default class alphService {
 stateObj = {
  sound: ""
 };
 getState(){
  this.stateObj.sound = require("../assets/sounds/c.mp3"); 
  return this.stateObj;
 }
}
Run Code Online (Sandbox Code Playgroud)

您可以创建一个包含所有路径的 json 文件并像这样使用它:

export default const paths = {
    file1: require("path/to/file1.png"),
    file2: require("path/to/file2.png")
}
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中导入此路径文件并像这样使用它(例如图像):

<Image source={paths.file1}/>
Run Code Online (Sandbox Code Playgroud)