英文:
How to toggle pause/play audio with button click in Pure Javascript?
问题
I find in Stackoverflow before but almost example working in
有没有办法在使用Javascript时切换单击播放/暂停?
HTML代码:
<button id="music" class="play-song"></button>
我的JS代码如下:
<script>
const elem = document.getElementById("music");
if (elem) {
elem.addEventListener ("click", playMusic, false);
}
function playMusic() {
var musik= new Audio("/songs/1.mp3");
musik.play();
var current = this;
if (current != elem) {
elem.classList.remove('mute-audio');
} else if (current.classList.contains('mute-audio') === true) {
current.classList.remove('mute-audio');
} else {
current.classList.add('mute-audio');
}
}
</script>
英文:
I find in Stackoverflow before but almost example working in <audio> element.
Have any method toggle click play/pause when using Javascript?
HTML Code:
<button id="music" class="play-song"></button>
My JS code look like:
<script>
const elem = document.getElementById("music");
if (elem) {
elem.addEventListener ("click", playMusic, false);
}
function playMusic() {
var musik= new Audio("/songs/1.mp3");
musik.play();
var current = this;
if (current != elem) {
elem.classList.remove('mute-audio');
} else if (current.classList.contains('mute-audio') === true) {
current.classList.remove('mute-audio');
} else {
current.classList.add('mute-audio');
}
}
</script>
答案1
得分: 1
以下是您要翻译的代码部分:
const elem = document.getElementById("music");
if (elem) {
elem.addEventListener("click", playMusic, false);
}
var musik = new Audio("https://xomkey.com/wp-content/uploads/songs/xomkey-song.mp3");
function playMusic() {
if (musik.paused) {
musik.play();
// do your other task
} else {
musik.pause();
// do your other task
}
}
<button id="music" class="play-song">播放/暂停</button>
希望这对您有所帮助。如果您有其他需要,请随时告诉我。
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const elem = document.getElementById("music");
if (elem) {
elem.addEventListener ("click", playMusic, false);
}
var musik= new Audio("https://xomkey.com/wp-content/uploads/songs/xomkey-song.mp3");
function playMusic() {
if(musik.paused){
musik.play();
// do your other task
} else {
musik.pause();
// do your other task
}
}
<!-- language: lang-html -->
<button id="music" class="play-song">Play/Pause</button>
<!-- end snippet -->
You can play and pause with this piece of code like toggle. For audio, there are many more interesting methods.
For your reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论