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();
})();
}
}
AlphService.js
export default class alphService {
stateObj = {
sound: ""
};
getState(){
this.stateObj.sound = "../assets/sounds/c.mp3";
return this.stateObj;
}
}
错误:components / Alphabet.js:第51行的无效调用:require(source)
,然后尝试
我从require(soundPathVar)
方法返回getState()
对象,并从play()
中删除了必需的对象,然后出现相同的错误。
我是react-native的初学者,我想尝试创建动态声音文件路径。如果我做错了,那么请您帮我。预先感谢。
答案 0 :(得分:2)
当我尝试使用require()动态图像时,我遇到了这个问题,结果发现即使require("SOURCE/" + "something.png")
不起作用,require只接受特定的源,应该是require("SOURCE/something.png")
。试试这个:
export default class alphService {
stateObj = {
sound: ""
};
getState(){
this.stateObj.sound = require("../assets/sounds/c.mp3");
return this.stateObj;
}
}
您可以创建一个包含所有路径的json文件,并按如下方式使用它:
export default const paths = {
file1: require("path/to/file1.png"),
file2: require("path/to/file2.png")
}
然后在您的组件中导入此路径文件并像这样使用它(例如图像):
<Image source={paths.file1}/>