使用audio.play()函数时出现反应错误
我试图通过在React中使用onClick事件触发函数来播放声音,但收到以下错误:
未捕获错误:您提供的错误不包含堆栈跟踪。
位于B(index.js:1582)
在G(index.js:1899)
at eval(index.js:1914)
at eval(index.js:1933)
at eval(index.js:1414)
import React from "react";
import firebase from "../../firebase";
import classes from "./Sidenav.module.sass";
const Sidenav = props => {
const logout = () => {
firebase.auth().signOut();
window.location.href = "..";
};
const playAudio = () => {
let audio = new Audio("../../assets/bellNotification.mp3");
audio.play();
};
return (
<div style={props.styles.sideNavDiv} className={classes.sidenavDiv}>
<i />
<div style={props.styles.iconDiv} className={classes.iconDiv}>
<i className={"material-icons " + classes.navIcon}>account_box</i>
<p className={classes.iconText}>Account</p>
</div>
<div style={props.styles.iconDiv} className={classes.iconDiv}>
<i className={"material-icons " + classes.navIcon}>settings</i>
<p className={classes.iconText}>Settings</p>
</div>
<div style={props.styles.iconDiv} className={classes.iconDiv}>
<i className={"material-icons " + classes.navIcon}>trending_up</i>
<p className={classes.iconText}>Check Progress</p>
</div>
<div style={props.styles.iconDiv} className={classes.iconDiv}>
<i className={"material-icons " + classes.navIcon}>looks_one</i>
<p className={classes.iconText}>1RM calculator</p>
</div>
<div
onClick={props.toggleModal}
style={props.styles.iconDiv}
className={classes.iconDiv}
>
<i className={"material-icons " + classes.navIcon}>alarm</i>
<p className={classes.iconText}>Edit timers</p>
</div>
<div
onClick={playAudio}
style={props.styles.iconDiv}
className={classes.iconDiv}
>
<i className={"material-icons " + classes.navIcon}>help</i>
<p className={classes.iconText}>Help</p>
</div>
<div
onClick={logout}
style={props.styles.iconDiv}
className={classes.iconDiv}
>
<i className={"material-icons " + classes.navIcon}>
power_settings_new
</i>
<p className={classes.iconText}>Logout</p>
</div>
</div>
);
};
export default Sidenav;
解决方案
同样的事情也发生在我身上,因为玩家承诺中的铬更改。
只需将player.play()
替换为
const playPromise = player.play();
if (playPromise !== undefined) {
playPromise
.then(_ => {
// Automatic playback started!
// Show playing UI.
console.log("audio played auto");
})
.catch(error => {
// Auto-play was prevented
// Show paused UI.
console.log("playback prevented");
});
}
您可以阅读有关它的更多信息here on chrome blogs about player promise changes
相关文章