如何使用一个按钮或链接切换音频播放()暂停()? [英] How to toggle audio play() pause() with one button or link?
问题描述
我有一个音频文件,当点击锚标签时播放。如果再次单击锚标签,我希望音频暂停,我只是不太了解JavaScript以便将此后半部分关闭。我不想更改他们点击的定位标记的内容,我只是希望音频文件在他们点击标记时开始并暂停。
这就是到目前为止,这至少使声音文件可以播放:
< audio id =audiosrc =/ Demo.mp3\" >< /音频>
< a onClick =document.getElementById('audio')。play()>点击这里收听。< / a>
Vanilla Javascript方式来完成您的要求。
注意:我注意到其他问题有多个upvotes针对本地js方法的评论,并且看到OP没有 因此 jquery $ c
工作示例
:
$ b $ p SOLN 1
:(我的初始使用事件)
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;};
< audio id =myAudiosrc =http://www.sousound.com/music/healing/healing_01.mp3preload = auto>< / audio>< a onClick =togglePlay()>点击此处收听。< / a>
var myAudio = document.getElementById(myAudio);函数togglePlay(){return myAudio.paused? myAudio.play():myAudio.pause();};
< audio id =myAudiosrc =http://www.sousound.com/music/healing/healing_01.mp3preload =auto>< / audio>< a onClick =togglePlay ()>点击这里收听。< / a>
I have an audio file that plays when an anchor tag is clicked. If the anchor tag is clicked again, I want the audio to pause, I just don't know enough about javascript to pull this second half off. I don't want to change the content of the anchor tag they click, I just want the audio file to start and pause whenever they click the tag.
This is what I have so far, which at least makes the sound file playable:
<audio id="audio" src="/Demo.mp3"></audio>
<a onClick="document.getElementById('audio').play()">Click here to hear.</a>
A Vanilla Javascript way to do what you required.
Note: I've noticed comments on other question with multiple upvotes for a native js approach and saw the OP has no jquery
tag.
So WORKING EXAMPLE
:
SOLN 1
: (my initial soln using events)
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;
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
SOLN 2
: (using myAudio.paused
property based on dandavi's comment)
var myAudio = document.getElementById("myAudio");
function togglePlay() {
return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
这篇关于如何使用一个按钮或链接切换音频播放()暂停()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!