Javascript警报不播放声音文件



我现在正在本地主机上工作,我的笔记本电脑。我是唯一的用户。

我为朋友做了一个在线考试。他问我是否可以在考试结束前5分钟响铃或留言,这样学生就不会等太久再按"发送",否则他们将无法发送答案。

我有这个JavaScript。有人告诉我这对他有用。看这里:

<script>
const d = new Date();
// if later than h, play the sound. It's past 11am here now!
// set the minutes later if this works
var h = d.getHours();
console.log({h});
if (h > 7) {
// I put a hidden input on the page, with the value of the sound file
// <input type="hidden" id="musicloc" size="55" value="mp3/fullstop.mp3" /> 
var sound = document.getElementById("musicloc").value;
playSound(sound);
}
// this should make an audio element and then play the sound            
function playSound(soundFile) {
var audioElement = document.createElement('audio');
// maybe here the problem? What is 'src'?
audioElement.setAttribute('src', soundFile);
audioElement.play();
</script>

但我没有声音。

在火狐中,我确实看到了此错误:

只有在用户批准后才允许自动播放,该网站是 由用户激活,或媒体静音。 19BEsW13.html:259:18

NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user

被拒绝的许可。

我无法让火狐重复此错误消息。

我无法打开

console.log({h}( 引用错误:未定义 h

这是火狐浏览器设置问题吗?我可以更改此设置吗?

或者以其他方式播放声音?

正如佩德罗斯基指出的那样,除非用户与页面交互,否则浏览器不允许播放声音。

解决此问题的一种方法是添加一个按钮,用户需要单击该按钮才能同意振铃提醒声音。

例如:

// javascript
let startBtn = document.getElementById("start")
startBtn.onclick = function (e) {
e.preventDefault()
let count = document.getElementById("count")
let interval = window.setInterval(function () {
count.textContent = --count.textContent;
if (count.textContent == 0) {
clearInterval(interval);
let bell = document.getElementById("bell")
bell.play()
}
}, 1000)
}
<!-- html -->
<audio id="bell">
<source
src="http://filipcicspagerprogramming.weebly.com/uploads/1/0/5/4/10541783/05-dive-n.wav"
/>
Your browser does not support the audio element.
</audio>
<p id="count" style="font-size: large;">5</p>
<button id="start">Remind After 5 Secs</button>

最新更新