javascript 使用 jQuery 控制 HTML5 <audio> 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9579938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:06:31  来源:igfitidea点击:

Using jQuery to control HTML5 <audio> element

javascriptjqueryhtmlaudio

提问by futureslay

I'm trying to use jQuery to control an HTML5 audio element, but I'm no genius with JS. What I want is for the player to start on page load, which I've done, but when the play button is clicked, I want to check whether or not the audio is playing. If it's playing when clicked: Stop the audio. If it's not playing when clicked: Play the audio.

我正在尝试使用 jQuery 来控制 HTML5 音频元素,但我对 JS 并不擅长。我想要的是让播放器在页面加载时开始,我已经完成了,但是当点击播放按钮时,我想检查音频是否正在播放。如果单击时正在播放:停止音频。如果单击时未播放:播放音频。

If you could help, it'd be much appreciated.

如果您能提供帮助,将不胜感激。

Source here: http://www.julake.co.uk/media/loader.php?page=contact

来源:http: //www.julake.co.uk/media/loader.php?page=contact

Many thanks,

非常感谢,

回答by Fabrizio Calderan

you should use a single play/pause toggle button in which you need to check if your audio is paused or not

您应该使用单个播放/暂停切换按钮,您需要在其中检查音频是否已暂停

var audioplayer = document.getElementById("audio-player");
$("#play-bt").click(function(){
    if (audioplayer.paused) {
       audioplayer.play();
    }   
    else {
       audioplayer.pause();
    }
    $(this).toggleClass('pause');  /* style your toggle button according to 
                                      the current state */
})

回答by Danny Fox

var audio = new Audio("http://www.w3schools.com/html5/song.ogg"); //or you can get it with getelementbyid

audio.addEventListener('canplay', function() {
//code, when audio can play
audio.play(); //this function will start the music
})

with audio.play() function you can start it. You don't need JQuery

使用 audio.play() 函数可以启动它。你不需要 JQuery

回答by Louise McMahon

If you wish to use a jquery selector or have a jquery selector already, you can add [0]to get the native dom element.

如果您希望使用 jquery 选择器或已经有一个 jquery 选择器,您可以添加[0]以获取本机 dom 元素。

So an example that actually uses jquery would be.

所以一个实际使用 jquery 的例子是。

$('audio')[0].pause()

$('audio')[0].pause()