首页 > 解决方案 > 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")
    }
  }

标签: reactjsreact-nativeexpo

解决方案


错误很简单,使用 require('soundpath.mp3) //sound 扩展名。


推荐阅读