gpt4 book ai didi

javascript - 浏览器选项卡处于非事件状态时如何在 REACT 应用程序中播放音频?

转载 作者:行者123 更新时间:2023-12-01 15:43:35 24 4
gpt4 key购买 nike

我正在尝试让 React 在计时器变为 0 时播放声音。计时器在使用 Reacts 引导模式组件构建的组件中运行。

如果运行应用程序的浏览器选项卡处于非事件状态,有时即使计数器达到 0 也不会播放声音,直到单击浏览器选项卡。单击选项卡时,声音会正常播放。 (在 Chrome 中测试)

state.timeLeft 变量正在正确更新,我编写了组件以将剩余时间百分比显示为选项卡标题,很明显即使计数器为 0 也不会播放声音。关于可能触发此行为的任何想法?感谢您的帮助:)

import React, {Component} from 'react'
import {Button, Modal, Image} from 'react-bootstrap'
import doneWav from '../sounds/sunny.wav'

class Pomodoro extends Component {
constructor(props) {
super(props)
this.state = {
timeLeft: this.props.time*60, //time left stored in seconds
}
this.targetDate = Date.parse(new Date()) + this.props.time*60*1000
}

componentDidMount() {
this.intervalId = setInterval( () => {
let timeLeft = ( this.targetDate - Date.parse(new Date()) )/1000
this.setState({timeLeft})
document.title = `${Math.round((timeLeft/(this.props.time*60))*100)}%`
if(timeLeft < 1) {
clearInterval(this.intervalId)
}
}, 500)
}

componentWillUnmount() {clearInterval(this.intervalId)}

render() {
const pomodoroIsRunning = this.state.timeLeft > 1
const playAudio = !pomodoroIsRunning ? <audio src={doneWav} autoPlay/> : null
const title = pomodoroIsRunning ?
`${this.props.activity.title} - ${this.state.timeLeft} sec left` :
`Hurray, job done !`
const button = pomodoroIsRunning ?
<Button variant="secondary" onClick={this.props.stop} className="">Stop</Button> :
<Button variant="primary" onClick={this.props.finish}>Claim Reward</Button>

return (
<>
{ playAudio }
<Modal

最佳答案

我认为这个问题与 this question 有关- the gist is, the audio won't play the first time it is loaded when the tab is unfocused as a browser performance optimization mechanic.不过,我已经设法找到一种方法来解决您的问题。您可以在 muted 时播放音频当用户第一次进入应用程序时。例如,我播放 muted组件最初安装时的音频。这样,当标签未聚焦时此音频的后续播放仍应播放。

componentDidMount() {
var audio = new Audio(doneWav);
audio.muted = true;
audio.play();
}

Edit React HTML5 Audio Unfocused Tab


旧答案:

如果您在 Chrome 上进行测试,我认为这与 Autoplay Policy Changes 有关- 要点是,autoplay (即 <audio src={doneWav} autoPlay />)失败,因为用户没有先与文档交互。事实上,如果您尝试创建新音频并执行 .play(),也会发生这种情况。在上面。

enter image description here

看看这个 CodeSandBox:https://codesandbox.io/s/wizardly-bash-9gswo?file=/src/App.js - 不要与浏览器选项卡交互,它不会播放并导致错误。但是,例如,如果您在计时器到期之前单击窗口上的任意位置,它应该会播放。

在我看来,某处可能有解决方法,但最终浏览器开发人员会考虑为这项新政策打补丁——你最好不要找到一个漏洞来避免对该功能进行持续的源代码维护,我反而建议寻找其他用户体验替代方案。

关于javascript - 浏览器选项卡处于非事件状态时如何在 REACT 应用程序中播放音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63859298/

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