如何使用一个按钮或链接切换音频播放()暂停()?

时间:2014-12-08 23:14:09

标签: javascript html audio

我有一个在点击锚标签时播放的音频文件。如果再次点击锚标签,我希望音频暂停,我只是不太了解javascript以拉下这一半。我不想更改他们点击的锚标记的内容,我只想让音频文件在他们点击标记时开始和暂停。

这是我到目前为止所做的,至少使声音文件可以播放:

<audio id="audio" src="/Demo.mp3"></audio>
<a onClick="document.getElementById('audio').play()">Click here to hear.</a>

5 个答案:

答案 0 :(得分:12)

Vanilla Javascript方式来做你需要的。

注意:我已经注意到其他问题的评论,其中有多个upvotes用于本地js方法,并且看到OP没有jquery标记。

所以 WORKING EXAMPLE

SOLN 1 :(我最初的使用事件处理)

&#13;
&#13;
var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
};
myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};
&#13;
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
&#13;
&#13;
&#13;

SOLN 2 :(使用基于 dandavi's commentmyAudio.paused属性)

&#13;
&#13;
var myAudio = document.getElementById("myAudio");

function togglePlay() {
  return myAudio.paused ? myAudio.play() : myAudio.pause();
};
&#13;
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

void send(string|array|MailableContract $view, array $data = [], Closure|string $callback = null)

答案 2 :(得分:2)

您可以使用jQuery为此进行切换。

<a id="music-button" style="cursor:pointer;">
<img src="http://i.stack.imgur.com/LT3WE.png"></a>
<audio id="playMusic" autoplay>
<source src="sound.mp3">
</audio>

<script type="text/javascript">
$('#music-button').toggle(
function () {
document.getElementById('playMusic').play();
},
function () {
document.getElementById('playMusic').pause();
}
);
</script>

答案 3 :(得分:0)

var Sample-Audio = document.getElementById("Sample");

function togglePlay() {
  return Sample-Audio.paused ? Sample-Audio.play() : Sample-Audio.pause();
};
<audio id="Sample" preload="auto">
  <source src="./sounds/rain.mp4" type="audio/mp4">
  <source src="./sounds/rain.ogg" type="video/ogg"> 
</audio>
<a onClick="togglePlay()">Click here to hear.</a>

答案 4 :(得分:0)

myAudio变量必须在函数调用中...可以正常工作

function togglePlay() {
  var myAudio = document.getElementById("myAudio");
  return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio 
id="myAudio" src="https://clubajax.pythonanywhere.com/media/contact/backgroundM.mp3" preload="auto">
</audio>

<input type="button" value="sound" onclick="togglePlay()" />