我想知道是否有任何方法可以克服谷歌新的自动播放政策。
我想在链接悬停时播放一个简短的声音片段,不幸的是它只适用于Firefox而不是Chrome和safari。有没有办法找到解决这个问题的方法?
可能不是我想的,只是想在这个领域向受过更多教育的人们提出这个问题。也许有人有想法。 :)
这个代码在firefox中工作,并且曾经在chrome和safari中工作 - 但现在不行了。
HTML
<span class="hit hitme">Just hit me up!</span>
<audio id="HitMe">
<source src="sound/hitmeup.mp3">
</audio>
jQuery的
var audio = $("#HitMe")[0];
$(".hitme").mouseenter(function() {
audio.play()
$(".hitme").mouseleave(function() {
audio.pause();
});
});
你的问题很短,但实际上有很多事情要说。
首先,在策略更改方面使用VanillaJS™而不是jQuery总是很好,因为标准立即传播到普通的JavaScript,而改变需要一段时间才能传播到第三方库,如jQuery。使用纯JavaScript的好处是你可以使用new Audio(<source>)
创建一个音频对象 - 不需要任何HTML元素!请参阅下面的示例:
const audio = new Audio("https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3");
// wait for the DOM to load
window.onload = () => {
// play audio on click
const clickToPlay = document.querySelector('#click-to-play');
clickToPlay.onclick = () => audio.play();
// play/pause audio on hover
const hoverToPlay = document.querySelector('#hover-to-play');
hoverToPlay.onmouseover = () => audio.play();
hoverToPlay.onmouseout = () => audio.pause();
}
/* just some styling, not useful for the solution */
#click-to-play {
padding: 1em;
background-color: steelblue;
}
#click-to-play:hover {
cursor: pointer;
}
#hover-to-play {
padding: 1em;
background-color: lightblue;
}
#hover-to-play:hover {
cursor: crosshair;
}
<div id="click-to-play">
Click to play
</div>
<div id="hover-to-play">
Hover in to play, hover out to pause
</div>
大!除非你准备好了,否则可能被the 2017 update on autoplay in Chrome阻止的悬停自动播放。
但这不一定是坏事。此更新旨在提高Web用户体验。如果您正试图找到如何绕过它的黑客攻击,那么您做错了;)更新声明如果用户进行了交互(例如点击),则允许自动播放声音。因此,在设计网站时,请确保用户在显示自动播放前点击页面上的某个位置。这是一个两步点击授权的示例,悬停以播放用户体验:
const audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
window.onload = () => {
const clickToAuthorize = document.querySelector('#click-to-authorize');
const hoverToPlay = document.querySelector('#hover-to-play');
clickToAuthorize.onclick = () => {
hoverToPlay.style.display = 'block';
}
hoverToPlay.onmouseover = () => audio.play();
hoverToPlay.onmouseout = () => audio.pause();
}
#click-to-authorize {
padding: 1em;
background-color: steelblue;
}
#click-to-authorize:hover {
cursor: pointer;
}
#hover-to-play {
padding: 1em;
background-color: lightblue;
display: none;
}
#hover-to-play:hover {
cursor: crosshair;
}
<div id="click-to-authorize">
Click if you want to hear a T-Rex roar!
</div>
<div id="hover-to-play">
Hover to play/pause
</div>