JavaScript警报无法播放声音文件

时间:2020-05-31 03:33:42

标签: javascript

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

我为一个朋友进行了在线考试。他问我是否可以在考试结束前5分钟响起铃声或发出消息,以使学生不要等太久才按“发送”,否则他们将无法发送答案。

我有这个javascript。有人告诉我这对他有用。看起来here

<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>

但是我没有声音。

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

仅当获得用户批准时才允许自动播放,该网站是 用户激活或媒体被静音。 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

被拒绝的权限。

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

我无法打开

console.log({h})ReferenceError:未定义h

这是Firefox设置问题吗?我可以改变这个吗?

还是以其他方式播放声音?

1 个答案:

答案 0 :(得分:1)

Pedroski所示,除非用户与页面互动,否则浏览器不允许播放声音。

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

例如:

// 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>