useEffect在使用HTMLAudioElement时抛出DOMException

问题描述 投票:1回答:1

我写了一个名为useAudio的自定义React钩子来播放我应用程序背景中的声音。

为什么useEffect投掷Uncaught (in promise) DOMException

我把问题缩小到我自定义钩子里面的第二个useEffect。当指示音频是否为playing的布尔值发生变化时,此效果会运行。

所有React都说是Uncaught Error: The error you provided does not contain a stack trace.

我也尝试将audio修改为常规常量而不是通过useState钩子声明,但这并没有解决它。

import React, { useState, useEffect } from 'react'
import styled from 'styled-components'

const useAudio = (url: string) => {
  if (typeof Audio !== 'undefined') {
    const [audio] = useState(new Audio(url))
    const [playing, setPlaying] = useState(false)

    const toggle = () => setPlaying(!playing)

    useEffect(() => {
      audio.loop = true
      audio.autoplay = true
    })

    useEffect(() => {
      playing ? audio.play() : audio.pause()
      return () => {
        audio.pause()
      }
    }, [playing])

    return [playing, toggle]
  }
}

const AudioPlayer: React.FC<{ url: string }> = ({ url }) => {
  if (typeof Audio !== 'undefined') {
    const [playing, toggle] = useAudio(url)

    return (
      <AudioContainer>
        {typeof playing !== 'undefined' && (
          <Button onClick={() => toggle()}>
            {playing ? 'Stop music' : 'Play music'}
          </Button>
        )}
      </AudioContainer>
    )
  }
  return null
}

export default AudioPlayer

它在live app工作。

它不是在这个孤立的Codesandbox工作。

我希望音频在安装组件时启动,并且不会抛出DOMExceptions。

javascript reactjs react-hooks
1个回答
1
投票

你有几个关于你的应用程序的模糊点,包括在条件中使用钩子并在状态中存储audio对象(尝试使用useRef,这是它的唯一目的)。但问题的核心似乎url,你喂Audioundefined。我猜CodeSandbox环境没有适合mp3文件的加载器。请尝试使用直接网址。

沙箱:https://codesandbox.io/s/l7775jm2rm

© www.soinside.com 2019 - 2024. All rights reserved.