Expo音频对象未处理的诺言拒绝,soundObject未定义-无法在创建它的函数外部访问对象

时间:2018-11-12 12:10:54

标签: reactjs react-native expo

我试图在props.sound == true时播放声音,并在props.sound = false时停止播放。我不断收到未处理的承诺拒绝错误和错误未定义对象。 这是我的代码:

do { } catch { }

我已经尝试过使用道具,状态等方法,但是只有在我将playAsync放在原始函数中(例如,

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();
    }
  }

1 个答案:

答案 0 :(得分:0)

错误很简单,请使用require('soundpath.mp3)//声音扩展。