Javascript 单击按钮时使用 jQuery 播放音频文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8489710/
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-08-24 06:12:54  来源:igfitidea点击:

Play an audio file using jQuery when a button is clicked

javascriptjqueryhtml

提问by Suresh Pattu

I am trying to play an audio file when I click the button, but it's not working, my html code is:

当我单击按钮时,我正在尝试播放音频文件,但它不起作用,我的 html 代码是:

<html>    
    <body>
        <div id="container">
            <button id="play">
                Play Music
            </button>
        </div>
    </body>
</html>

my JavaScript is :

我的 JavaScript 是:

$('document').ready(function () {
    $('#play').click(function () {
        var audio = {};
        audio["walk"] = new Audio();
        audio["walk"].src = "http://www.rangde.org/static/bell-ring-01.mp3"
        audio["walk"].addEventListener('load', function () {
            audio["walk"].play();
        });
    });
});   

I have created a Fiddlefor that too.

我也为此创建了一个小提琴

回答by Ahmet Can Güven

Which approach?

哪种方法?

You can play audio with <audio>tag or <object>or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play()and pause it with .pause().

您可以使用<audio>标签或<object>或播放音频<embed>。延迟加载(在需要时加载)声音是最好的方法,如果它的大小很小。您可以动态创建音频元素,当它加载时,您可以.play()使用.pause().

Things we used

我们用过的东西

We will use canplayevent to detect our file is ready to be played.

我们将使用canplay事件来检测我们的文件是否准备好播放。

There is no .stop()function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop()function we first pause the file then reset its time.

没有.stop()音频元素的功能。我们只能暂停他们。当我们想从音频文件的开头开始时,我们将其.currentTime. 我们将在我们的示例中使用这一行audioElement.currentTime = 0;。为了实现.stop()功能,我们首先暂停文件然后重置其时间。

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

我们可能想知道音频文件的长度和当前播放时间。我们已经在.currentTime上面学习过,为了了解它的长度,我们使用.duration.

Example Guide

示例指南

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.
  1. 当文档准备好时,我们动态地创建了一个音频元素
  2. 我们用我们想要播放的音频设置它的源。
  3. 我们使用“结束”事件再次启动文件。

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

当 currentTime 等于其持续时间时,音频文件将停止播放。无论何时使用play(),它都会从头开始。

  1. We used timeupdateevent to update current time whenever audio .currentTimechanges.
  2. We used canplayevent to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.
  1. 我们使用timeupdate事件来在音频.currentTime发生变化时更新当前时间。
  2. canplay当文件准备好播放时,我们使用事件来更新信息。
  3. 我们创建了播放、暂停、重启按钮。

$(document).ready(function() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');
    
    audioElement.addEventListener('ended', function() {
        this.play();
    }, false);
    
    audioElement.addEventListener("canplay",function(){
        $("#length").text("Duration:" + audioElement.duration + " seconds");
        $("#source").text("Source:" + audioElement.src);
        $("#status").text("Status: Ready to play").css("color","green");
    });
    
    audioElement.addEventListener("timeupdate",function(){
        $("#currentTime").text("Current second:" + audioElement.currentTime);
    });
    
    $('#play').click(function() {
        audioElement.play();
        $("#status").text("Status: Playing");
    });
    
    $('#pause').click(function() {
        audioElement.pause();
        $("#status").text("Status: Paused");
    });
    
    $('#restart').click(function() {
        audioElement.currentTime = 0;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Sound Information</h2>
    <div id="length">Duration:</div>
    <div id="source">Source:</div>
    <div id="status" style="color:red;">Status: Loading</div>
    <hr>
    <h2>Control Buttons</h2>
    <button id="play">Play</button>
    <button id="pause">Pause</button>
    <button id="restart">Restart</button>
    <hr>
    <h2>Playing Information</h2>
    <div id="currentTime">0</div>
</body>

回答by felwithe

$("#myAudioElement")[0].play();

It doesn't work with $("#myAudioElement").play()like you would expect. The official reason is that incorporating it into jQuery would add a play()method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement"), aka 0.

$("#myAudioElement").play()不像你期望的那样工作。官方原因是将其合并到 jQuery 中会play()为每个元素添加一个方法,这会导致不必要的开销。因此,您必须通过它在检索的 DOM 元素数组中的位置来引用它$("#myAudioElement"),也就是 0。

This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":

此引用来自提交的关于它错误,错误已关闭为“功能/不会修复”:

To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.

为此,我们需要为每个 DOM 元素方法名称添加一个 jQuery 方法名称。当然,该方法对非媒体元素没有任何作用,因此似乎不值得花费额外的字节。

回答by texas-bronius

For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:

对于其他任何人,我只是简单地接受了 Ahmet 的回答并在此处更新了原始提问者的jsfiddle,替换为:

audio.mp3

for

为了

http://www.uscis.gov/files/nativedocuments/Track%2093.mp3

linking in a freely available mp3 off the web. Thank you for sharing the easy solution!

链接在网络上免费提供的 mp3。感谢您分享简单的解决方案!

回答by André R. Kohl

I here have a nice and versatile solution with a fallback:

我在这里有一个很好的多功能解决方案,带有后备:

<script type="text/javascript">
    var audiotypes={
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }

    function ss_soundbits(sound){
        var audio_element = document.createElement('audio')
        if (audio_element.canPlayType){
            for (var i=0; i<arguments.length; i++){
                var source_element = document.createElement('source')
                source_element.setAttribute('src', arguments[i])
                if (arguments[i].match(/\.(\w+)$/i))
                    source_element.setAttribute('type', audiotypes[RegExp.])
                audio_element.appendChild(source_element)
            }
            audio_element.load()
            audio_element.playclip=function(){
                audio_element.pause()
                audio_element.currentTime=0
                audio_element.play()
            }
            return audio_element
        }
    }
</script>

After that you can initialize as many audio as you like:

之后,您可以根据需要初始化任意数量的音频:

<script type="text/javascript" >
    var clicksound  = ss_soundbits('your/path/to/click.ogg', "your/path/to/click.mp3");
    var plopsound  = ss_soundbits('your/path/to/plopp.ogg', "your/path/to/plopp.mp3");
</script>

Now you can reach the initialized audio element whereever you like with simple event calls like

现在,您可以通过简单的事件调用,随时随地访问已初始化的音频元素,例如

onclick="clicksound.playclip()"

onmouseover="plopsound.playclip()"

回答by Jeff

JSFiddle Demonstration

JSFiddle 演示

This is what I use with JQuery:

这是我与 JQuery 一起使用的:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

回答by Luis David

What about:

关于什么:

$('#play').click(function() {
  const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");
  audio.play();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>