reactjs - Expo 音频对象未处理的承诺拒绝,soundObject 未定义 - 无法访问创建它的函数之外的对象
问题描述
我试图在 props.sound==true 时播放声音,并在 props.sound=false 时停止。我不断收到未处理的承诺拒绝错误和错误未定义的对象。这是我的代码:
constructor(props)
{super(props);
this.soundObject = new Expo.Audio.Sound();
}
stopSound = async () => {
await this.soundObject.stopAsync();
}
playSound = async () => {
try{
await this.soundObject.playAsync();
}catch(error){
this.createSound()
await this.soundObject.playAsync();
}
}
componentWillMount(){
this.createSound();
}
componentWillUnmount(){
this.stopSound();
}
createSound = async() => {
try {
await this.soundObject.loadAsync(require('soundpath'));
await this.soundObject.setVolumeAsync(0.3)
await this.soundObject.setIsLoopingAsync(true)
} catch (error) {
console.log("sound couldn't load")
}
}
componentDidMount(){
if (this.props.sound==true){
this.playSound();
} else {
this.stopSound();
}
}
我已经尝试过使用道具,使用状态等,但它只有在我将 playAsync 放在原始函数中时才有效,即
createSound = async() => {
try {
soundObject = new Expo.Audio.Sound();
await soundObject.loadAsync(require('soundpath'));
await soundObject.setVolumeAsync(0.3)
await soundObject.setIsLoopingAsync(true)
await soundObject.playAsync()
} catch (error) {
console.log("sound couldn't load")
}
}
解决方案
错误很简单,使用 require('soundpath.mp3) //sound 扩展名。
推荐阅读
- javascript - 如何在反应组件中显示 API 数据?
- json - 无法使用火花提交读取本地 JSON 文件
- java - Netbeans 11 未检测到带有 JDK 12 的 JavaFX 应用程序的依赖项
- tensorflow - 了解训练期间的输出 - 持续时间是什么意思以及 TF 在两个时期之间做什么?
- docker - 动态应用完成选项
- javascript - 如何将图像放在圆形图上
- gams-math - 在 GAMS 中比较两个参数是否相同
- scroll - Flutter:使用 SingleChildScrollView 滚动时如何更改状态栏颜色
- javascript - 我无法使用 page.goto() 从一个页面转到另一个页面 - Puppeteer
- r - 用另一个向量的最小值创建向量 [R]