2

我正在扩展计时器组件的功能,以便为计时器的最后 3 秒添加beep声音。效果很好,问题毕竟是说完了。我正在执行以下操作:

  1. 将计时器组件包装在新的功能组件上
  2. Audio.Sound()在组件的主体中初始化
  3. 最初useEffect用于加载声音
  4. 在每个计时器事件中,我检查是否应该播放声音并使用replayAsync
  5. useEffect清理时我卸载声音对象unloadAsync

在最后一次哔声播放后大约一秒钟并且我导航到以下屏幕,我收到一个错误,我将在下面完整地过去。似乎 expo-av 库对我的声音对象调用了查找操作,但我的组件不再存在:

[Unhandled promise rejection: Error: Seeking interrupted.]

我尝试了以下但没有成功:

  • 拨打电话loadAsyncunloadAsync等待电话
  • 试图为setOnPlaybakStatusUpdatenull 以尝试阻止 statusUpdate 调用
  • 我什至试图不通过卸载声音unloadAsync

我的代码是:

import React from 'react'
import CountDown from 'react-native-countdown-component'
import { Audio } from 'expo-av'
const BEEP_START = 3

const CountDownBeep = (props) => {
  console.log('Sound Created')
  const beepSound = new Audio.Sound()

  React.useEffect(() => {
      async function loadSound() {
          console.log("Sound Initialized")
          await beepSound.loadAsync(require('../assets/sounds/beep.wav'), {
              shouldPlay: false,
              isLooping: false,
          })
          // This is not by design, just one of my attempts to get rid of the error
          beepSound.setOnPlaybackStatusUpdate()
      }

      loadSound()

      // Cleanup, tried with async and without
      return async () => {
          console.log('Sound destroyed')
          await beepSound.unloadAsync()
      }
  })

  const countDownTimerChangedHandler = (timeLeft) => {

      // This works fine
      if (timeLeft <= BEEP_START + 1 && timeLeft > 0) {
          console.log('Sound Played:', timeLeft)
          beepSound.replayAsync()
      }
  }

  return (
      <CountDown
          {...props}
          onChange={(timeLeft) => countDownTimerChangedHandler(timeLeft)}
      />
  )
}

export default CountDownBeep

功能是 100%,但是在我导航到下一个屏幕后几毫秒或一两秒后,我收到以下错误:

[Unhandled promise rejection: Error: Seeking interrupted.]
- node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:103:50 in promiseMethodWrapper
- node_modules/@unimodules/react-native-adapter/build/NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
- node_modules/expo-av/build/Audio/Sound.js:138:24 in replayAsync
- node_modules/expo-av/build/Audio/Sound.js:5:33 in <anonymous>
- node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
- node_modules/regenerator-runtime/runtime.js:293:29 in invoke
- node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
- node_modules/regenerator-runtime/runtime.js:154:27 in invoke
- node_modules/regenerator-runtime/runtime.js:189:16 in PromiseImpl$argument_0
- node_modules/promise/setimmediate/core.js:45:6 in tryCallTwo
- node_modules/promise/setimmediate/core.js:200:22 in doResolve
- node_modules/promise/setimmediate/core.js:66:11 in Promise
- node_modules/regenerator-runtime/runtime.js:188:15 in callInvokeWithMethodAndArg
- node_modules/regenerator-runtime/runtime.js:211:38 in enqueue
- node_modules/regenerator-runtime/runtime.js:238:8 in exports.async
- node_modules/expo-av/build/Audio/Sound.js:5:33 in <anonymous>
- node_modules/expo-av/build/Audio/Sound.js:5:33 in <anonymous>
- node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
- node_modules/regenerator-runtime/runtime.js:293:29 in invoke
- node_modules/regenerator-runtime/runtime.js:63:36 in tryCatch
- node_modules/regenerator-runtime/runtime.js:154:27 in invoke
- node_modules/regenerator-runtime/runtime.js:189:16 in PromiseImpl$argument_0
- node_modules/promise/setimmediate/core.js:45:6 in tryCallTwo
- node_modules/promise/setimmediate/core.js:200:22 in doResolve
- node_modules/promise/setimmediate/core.js:66:11 in Promise
- node_modules/regenerator-runtime/runtime.js:188:15 in callInvokeWithMethodAndArg
- node_modules/regenerator-runtime/runtime.js:211:38 in enqueue
- node_modules/regenerator-runtime/runtime.js:238:8 in exports.async
- node_modules/expo-av/build/Audio/Sound.js:5:33 in <anonymous>
* components/CountDownBeep.js:31:24 in countDownTimerChangedHandler
* components/CountDownBeep.js:39:22 in CountDown.props.onChange
- node_modules/react-native-countdown-component/index.js:115:21 in CountDown#updateTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:135:14 in _callTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:387:16 in callTimers
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
4

2 回答 2

1

另一个解决方案对我不起作用。我尝试成功摆脱这种寻求中断错误的方法是在 componentDidMount 中加载特定屏幕所需的所有声音。然后,您可以在整个文件中随意使用它们。

    // This would be a function in your component class
    componentDidMount = () => {
        this.loadSounds();
   };
// You can put SoundUtils in any file!
    export const SoundUtils = {
        loadSound: async (requiredSound: AVPlaybackSource) => {
            try {
                const { sound } = await Audio.Sound.createAsync(requiredSound, {
                shouldPlay: false,
                progressUpdateIntervalMillis: 1, //It doesn't need to be this low
            });
                return sound;
            } catch (error) {
                console.log(`Sound not loaded error: ${error}`);
            }
        },
    } 
    // This would be a function in your component class
    loadsounds = () => {
        const workoutStartSound = await SoundUtils.loadSound(require("../assets/sounds/workoutStart.wav"));
        const timeToWorkoutSound = await SoundUtils.loadSound(require("../assets/sounds/timeToWork.mp3"));
    // Now to make sure you're only working with an "accepted promise"
    if (workoutStartSound !== undefined) {
      // workoutStartSound is a property of the Component class and is of type Audio.Sound
      this.workoutStartSound = workoutStartSound;
    } else {
      console.log(`Workout Start sound was not set`);
    }
    if (timeToWorkoutSound !== undefined) {
      this.timeToWorkoutSound = timeToWorkoutSound;
    } else {
      console.log(`Time to Workout sound was not set`);
    }   

预先加载声音将是避免中断搜索的最佳方法!

    playSound = async () => {
        try {
            await this.workoutStartSound.playFromPositionAsync(0);
            // await this.timeToWorkoutSound.playFromPositionAsync(0);
        } catch (error) {
            console.log(`Error in start timer - ${error}`);
        }
    };
于 2021-10-17T05:05:26.590 回答
1

我想我已经修好了。问题不在于声音 API 或expo-av. 问题似乎是有问题的计时器组件如何处理回调。我怀疑,由于下一个屏幕也有一个组件,因此该组件以某种方式将新回调触发到旧组件中。我为组件的每个实例添加了唯一 ID,并且不再出现错误:

 <CountDown
            {...props}
            id={new Date().toTimeString()}
            onChange={(timeLeft) => countDownTimerChangedHandler(timeLeft)}
        />

注意:因此,我相信这个问题和答案只有在您使用https://github.com/talalmajali/react-native-countdown-component时才有意义。

感谢您的阅读。

于 2020-08-19T16:03:29.860 回答