reactjs - React Native - SetTimeout() 不工作。 t.apply

我正尝试在延迟一段时间后播放音频

_onPlayPausePressed = () => {
    if (this.sound != null) {
      if (this.state.isPlaying) {
        this.sound.pauseAsync();
      } else {
        setTimeout(this.sound.playAsync(), 2000);
      }
    }
  };

但是它返回错误:t.apply 不是一个函数。 (In't.apply(void 0,o)','t.apply' 未定义) 我尝试了 Oleg 的更新方法。它第一次工作,但之后就不会再运行了。以下是我的代码的更多见解:

//import the array with sound details:{id, name desc, sound}
import { soundArray } from "./CreateRecord";
...
export default class CurrentRecord extends React.Component {
  constructor(props) {
    super(props);
    this.currentSound = [];
    this.recording = null;
    this.sound = null;
    this.isSeeking = false;
    this.shouldPlayAtEndOfSeek = false;
    this.state = {
      haveRecordingPermissions: false,
      isLoading: false,
      isPlaybackAllowed: false,
      muted: false,
      soundPosition: null,
      soundDuration: null,
      recordingDuration: null,
      shouldPlay: false,
      isPlaying: false,
      isRecording: false,
      fontLoaded: false,
      shouldCorrectPitch: true,
      volume: 1.0,
      rate: 1.0,
      isModalVisible: false
    };
    this.recordingSettings = JSON.parse(
      JSON.stringify(Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY)
    );
  }

//load the audio when the component mount
  componentDidMount() {
    this.loadAudio();

    (async () => {
      await Font.loadAsync({
        "cutive-mono-regular": require("../../assets/fonts/CutiveMono-Regular.ttf")
      });
      this.setState({ fontLoaded: true });
    })();
    this._askForPermissions();
  }

//load the sound
  async loadAudio() {
    const { navigation } = this.props;
    const id = navigation.getParam("id");
    this.sound = new Audio.Sound();
    for (let i = 0; i < soundArray.length; i++) {
      if (soundArray[i].id === id) {
        this.currentSound = soundArray[i];
        console.log(this.currentSound);

        break;
      }
    }
    try {
      await this.sound.loadAsync({
        uri: this.currentSound.sound /* url for your audio file */
      });
      await this.sound.setOnPlaybackStatusUpdate(
        this._updateScreenForSoundStatus
      );
    } catch (e) {
      console.log("ERROR Loading Audio", e);
    }
  }

//change screen based on the status
  _updateScreenForSoundStatus = status => {
    if (status.isLoaded) {
      this.setState({
        soundDuration: status.durationMillis,
        soundPosition: status.positionMillis,
        shouldPlay: status.shouldPlay,
        isPlaying: status.isPlaying,
        rate: status.rate,
        muted: status.isMuted,
        volume: status.volume,
        shouldCorrectPitch: status.shouldCorrectPitch,
        isPlaybackAllowed: true
      });
    } else {
      this.setState({
        soundDuration: null,
        soundPosition: null,
        isPlaybackAllowed: false
      });
      if (status.error) {
        console.log(`FATAL PLAYER ERROR: ${status.error}`);
      }
    }
  };

  _askForPermissions = async () => {
    const response = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
    this.setState({
      haveRecordingPermissions: response.status === "granted"
    });
  };

//here's where i want to delay the audio file. 
  _onPlayPausePressed = () => {
    if (this.sound != null) {
      if (this.state.isPlaying) {
        this.sound.pauseAsync();
      } else {
        setTimeout(() => this.sound.playAsync(), 2000);
      }
    }
  };

  _onStopPressed = () => {
    if (this.sound != null) {
      this.sound.stopAsync();
    }
  };

  _onMutePressed = () => {
    if (this.sound != null) {
      this.sound.setIsMutedAsync(!this.state.muted);
    }
  };

  _onVolumeSliderValueChange = value => {
    if (this.sound != null) {
      this.sound.setVolumeAsync(value);
    }
  };

  _trySetRate = async (rate, shouldCorrectPitch) => {
    if (this.sound != null) {
      try {
        await this.sound.setRateAsync(rate, shouldCorrectPitch);
      } catch (error) {
        // Rate changing could not be performed, possibly because the client's Android API is too old.
      }
    }
  };

  _onRateSliderSlidingComplete = async value => {
    this._trySetRate(value * RATE_SCALE, this.state.shouldCorrectPitch);
  };

  _onPitchCorrectionPressed = async value => {
    this._trySetRate(this.state.rate, !this.state.shouldCorrectPitch);
  };

  _onSeekSliderValueChange = value => {
    if (this.sound != null && !this.isSeeking) {
      this.isSeeking = true;
      this.shouldPlayAtEndOfSeek = this.state.shouldPlay;
      this.sound.pauseAsync();
    }
  };

  _onSeekSliderSlidingComplete = async value => {
    if (this.sound != null) {
      this.isSeeking = false;
      const seekPosition = value * this.state.soundDuration;
      if (this.shouldPlayAtEndOfSeek) {
        this.sound.playFromPositionAsync(seekPosition);
      } else {
        this.sound.setPositionAsync(seekPosition);
      }
    }
  };

  _getSeekSliderPosition() {
    if (
      this.sound != null &&
      this.state.soundPosition != null &&
      this.state.soundDuration != null
    ) {
      return this.state.soundPosition / this.state.soundDuration;
    }
    return 0;
  }

  _getMMSSFromMillis(millis) {
    const totalSeconds = millis / 1000;
    const seconds = Math.floor(totalSeconds % 60);
    const minutes = Math.floor(totalSeconds / 60);

    const padWithZero = number => {
      const string = number.toString();
      if (number < 10) {
        return "0" + string;
      }
      return string;
    };
    return padWithZero(minutes) + ":" + padWithZero(seconds);
  }

  _getPlaybackTimestamp() {
    if (
      this.sound != null &&
      this.state.soundPosition != null &&
      this.state.soundDuration != null
    ) {
      return `${this._getMMSSFromMillis(
        this.state.soundPosition
      )} / ${this._getMMSSFromMillis(this.state.soundDuration)}`;
    }
    return "";
  }

  _getRecordingTimestamp() {
    if (this.state.recordingDuration != null) {
      return `${this._getMMSSFromMillis(this.state.recordingDuration)}`;
    }
    return `${this._getMMSSFromMillis(0)}`;
  }

最佳答案

改为

_onPlayPausePressed = () => {
    if (this.sound != null) {
      if (this.state.isPlaying) {
       this.sound.pauseAsync();
          } else {
         setTimeout(()=>this.sound.playAsync(), 2000);
      }
    }
  };

关于reactjs - React Native - SetTimeout() 不工作。 t.apply 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262589/

相关文章:

php - 如何修复 stripe-php 没有这样的 payment_method 错误

angular - 运行 karma 测试时出现错误无法读取 null 的属性 'extras'

firebase - 使用 react-native-firebase 在 React Native

image - fluttercandies extended_image.如何用 1 根手指双击而

typescript - 排版组件

ios - 如何使用 SPM 和 Xcode11 将二进制文件与库链接

asp.net-core-webapi - .NET Core 3 API - 在一个请求后停止工作

c# - 是否可以动态更改 ToolbarItem 的图标?

reactjs - 如何在更改层次结构后保持状态并防止重新渲染 react 组件?

reactjs - 如何在加载时打开 React Native Maps 标记的标注