解决 Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互
Posted
技术标签:
【中文标题】解决 Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互【英文标题】:Solve Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first 【发布时间】:2021-05-21 08:58:31 【问题描述】:我尝试使用 javascript 制作 html 页面以在鼠标悬停时播放声音,但是当我尝试在 chrome 浏览器上首次重新加载代码时,它给了我这个错误。我如何在 chrome 中解决这个问题。
Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互。
<html>
<head>
<title>ضمور العضلات</title>
<style>
.img-container
text-align: center;
</style>
<!-- Font Awesome -->
</head>
<audio id="musicSound" preload="auto" src="disability/sounds/song.mp3"
>
</audio>
<audio id="hungrySound" preload="auto" src="disability/sounds/water.mp3"
>
</audio>
<body style="background: #E8E8E8;">
<div class="container">
<div class="row" style="margin-top: 30px;">
<div class="col-md">
<img id="thirsty" onmouseover="playHungry()" src="disability/images/hungry_icon.png" class="img-thumbnail" title="أنا جائع">
</div>
</div>
<div class="row" style="margin-top: 130px;">
<div class="col-md" >
<img id="music" onmouseover="playMusic()" src="disability/images/music_icons.png" class="img-thumbnail" title="شغل الموسيقى">
</div>
</div>
</div>
<script>
var music = document.getElementById("musicSound");
var hungry= document.getElementById("hungrySound");
function playMusic()
music.play();
thirsty.pause();
thirsty.currentTime = 0;
function playHungry()
hungry.play();
music.pause();
music.currentTime = 0;
</script>
</body>
</html>
【问题讨论】:
您好,我建议您将音频标签移到文档正文中 我试过你的答案,但它显示相同的信息 【参考方案1】:我建议您在onmouseover
事件上创建audio
节点:
HTML
<div class="container">
<div class="row" style="margin-top: 30px;">
<div class="col-md">
<img id="thirsty" onmouseover="play('disability/sounds/water.mp3')" src="disability/images/hungry_icon.png" class="img-thumbnail" title="أنا جائع">
</div>
</div>
<div class="row" style="margin-top: 130px;">
<div class="col-md">
<img id="music" onmouseover="play('isability/sounds/song.mp3')" src="disability/images/music_icons.png" class="img-thumbnail" title="شغل الموسيقى">
</div>
</div>
</div>
<script>
const audio = document.createElement("audio");
audio.muted = true;
function play(src)
audio.pause();
audio.muted = false;
const source = document.createElement("source");
source.src = src;
audio.appendChild(source);
audio.currentTime = 0;
audio.play();
</script>
【讨论】:
我尝试了这段代码,但没有工作它显示相同的消息 尝试使用 audio.muted = true;以上是关于解决 Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互的主要内容,如果未能解决你的问题,请参考以下文章
前端Uncaught (in promise) 的解决方法及原因
如何解决问题:Uncaught (in promise) TypeError: promisify is not a function?
解决 Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互
如何解决“Uncaught (in promise) TypeError: response.body.forEach is not a function”? (vue.js 2)
解决vue3 vue-pdf报错Uncaught (in promise) TypeError: h is not a function
解决vue3 vue-pdf报错Uncaught (in promise) TypeError: h is not a function