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


93

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

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

我的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();
        });
    });
});   

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


您使用的是HTML5 音频
OnesimusUnbound 2011年

Answers:


145

哪种方法?

您可以使用<audio>标签或<object>或播放音频<embed>。延迟加载(需要时加载)如果声音较小,则声音是最佳方法。您可以动态创建音频元素,在加载音频元素时可以使用来启动.play()和暂停.pause()

我们使用的东西

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

.stop()音频元素没有任何功能。我们只能暂停它们。而且,当我们要从音频文件的开头开始时,请更改其.currentTime。我们将在示例中使用此行audioElement.currentTime = 0;。要实现此.stop()功能,我们首先暂停文件,然后重置其时间。

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

范例指南

  1. 准备好文档后,我们会动态创建一个音频元素
  2. 我们用想要播放的音频设置其来源。
  3. 我们使用了'ended'事件来再次启动文件。

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

  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>


1
而且您必须将此脚本放在<body> *的末尾
tbleckert 2011年

是一个大多数在所有浏览器中都有效的标记。
shaijut

非常好,尽管OP明确表示他想在jQuery中做到这一点。在您的示例中,您将使用纯JavaScript进行dom操作和事件侦听器。
雅克

我对以下代码段有疑问:mp3结束后如何自动停止音频?现在,我的音频很短,这声音继续循环播放
Domenico Monaco

1
@DomenicoMonaco只需删除ended从头开始播放音频的事件即可。
艾哈迈德·坎·古文

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

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

此引用来自提交的有关此错误的错误,错误已关闭为“功能/错误修正”:

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


3
谢谢!正是我想要的!
utdrmac

21

对于后续的其他人,我只是采用了Ahmet的答案,并在此处更新了原始askerjsfiddle,替换为:

audio.mp3

对于

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

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


在Ubuntu上的Firefox 42上运行
Bojan Kogoj 2015年

1
加载事件不会在Chrome中的此jsfiiddle中触发。它仅由于autoplay属性而播放。
汤姆(Tom)

12

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

<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.$1])
                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>

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

<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>

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

onclick="clicksound.playclip()"

onmouseover="plopsound.playclip()"

4

JSFiddle演示

这就是我使用的JQuery:

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

4

关于什么:

$('#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>


这是最简单的方法,就像一个咒语一样,您可以根据需要使用vanilla js事件触发相同的操作。
Andrea Mauro
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.