gpt4 book ai didi

javascript - 使用 HTMLAudioElement 时 useEffect 抛出 DOMException

转载 作者:行者123 更新时间:2023-11-30 19:39:15 25 4
gpt4 key购买 nike

我写了一个名为 useAudio 的自定义 React 钩子(Hook)在我的应用程序的后台播放声音。

为什么是useEffect throw Uncaught (in promise) DOMException

我已将问题缩小到第二个 useEffect在我的自定义 Hook 中。当指示音频是否为 playing 的 bool 值时运行此效果。变化。

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

我也试过修改audio成为一个常规常量,而不是通过 useState 声明 Hook ,但这并没有解决问题。

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。

最佳答案

关于您的应用程序,您有几个模糊的地方,包括在条件中使用 Hook 和在状态中存储 audio 对象(尝试使用 useRef,这是它的唯一目的)。但问题的核心似乎是您提供给 Audiourlundefined。我猜想 CodeSandbox 环境没有适合 mp3 文件的加载程序。尝试使用一些直接 URL。

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

关于javascript - 使用 HTMLAudioElement 时 useEffect 抛出 DOMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55584063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com