暂停和取消暂停功能中的音频

Pausing and Unpausing Audio in A Function

本文关键字:暂停 音频 功能 取消      更新时间:2023-09-26

我的网站在加载时播放音乐,但我也希望能够点击按钮暂停或取消暂停音乐。特别是对于自动播放或.onload不起作用的OSX。然而,我不确定onclick事件哪里出了问题。

<script type="text/javascript">
var audio = new Audio('/Sounds/Macintosh.mp3');
function detectmob() { 
         if( navigator.userAgent.match(/Android/i) //Checks if on mobile
         || navigator.userAgent.match(/webOS/i)
         || navigator.userAgent.match(/iPhone/i)
         || navigator.userAgent.match(/iPad/i)
         || navigator.userAgent.match(/iPod/i)
         || navigator.userAgent.match(/BlackBerry/i)
         || navigator.userAgent.match(/Windows Phone/i)
         ){
              return true;
          }
         else {
              var audio = new Audio('/Sounds/Macintosh.mp3');
              audio.play(); 
              }
}
function Pause {
    if (audio.play = false){
    audio.play();
    }
    else {
    audio.pause();
    }

}
window.onload = detectmob;
</script>
<center> <input type="image" onclick="Pause" src="/images/button.jpg" style="width:750px;height:400px;"></center>

在我实现了第二个功能(Pause)后,第一个功能停止工作。现在没有声音播放,与点击图片无关。

几个问题。

看起来您忘记在函数名称后添加括号(),您需要这些括号来调用函数。

function Pause {
    if (audio.play = false){
    audio.play();
    }
    else {
    audio.pause();
    }
}

应该是这样的:

function Pause() {
    if (audio.play = false){
    audio.play();
    }
    else {
    audio.pause();
    }   
}

您还忘记将它们添加到onclick定义中。

<input type="image" onclick="Pause" src="/images/button.jpg" style="width:750px;height:400px;">

应为:

<input type="image" onclick="Pause()" src="/images/button.jpg" style="width:750px;height:400px;">

你的代码整体应该是这样的:

<script type = "text/javascript" >
  var audio = new Audio('/Sounds/Macintosh.mp3');
function detectmob() {
  if (navigator.userAgent.match(/Android/i) //Checks if on mobile
    || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)
  ) {
    return true;
  } else {
    var audio = new Audio('/Sounds/Macintosh.mp3');
    audio.play();
  }
}
function Pause() {
  if (audio.play = false) {
    audio.play();
  } else {
    audio.pause();
  }

}
window.onload = detectmob();
</script> 
<center>
  <input type="image" 
               onclick="Pause()"
               src = "/images/button.jpg"
               style = "width:750px; height:400px;">
</center>