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

Sur*_*ttu 85 html javascript jquery

我点击按钮时尝试播放音频文件,但它不起作用,我的HTML代码是:

<html>    
    <body>
        <div id="container">
            <button id="play">
                Play Music
            </button>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的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();
        });
    });
});   
Run Code Online (Sandbox Code Playgroud)

我也为此创造了一个小提琴.

Ahm*_*ven 138

哪种方法?

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

我们用的东西

我们将使用canplay事件来检测我们的文件是否可以播放.

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

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

示例指南

  1. 文档准备就绪后,我们动态创建了一个音频元素
  2. 我们用我们想要播放的音频设置它的来源.
  3. 我们使用'已结束'事件再次启动文件.

当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;
    });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • @DomenicoMonaco 只需删除从头开始播放音频的“结束”事件即可。 (2认同)

fel*_*the 41

jQuery中的实际答案是

$("#myAudioElement")[0].play();
Run Code Online (Sandbox Code Playgroud)

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

此引用来自提交的有关它错误,错误已关闭为"feature/wontfix":

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

  • 谢谢!正是我在寻找的! (3认同)

tex*_*ius 21

对于跟随的其他人,我只是采取了艾哈迈德的答案,并在这里更新了原始提问者的jsfiddle,代替:

audio.mp3
Run Code Online (Sandbox Code Playgroud)

对于

http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
Run Code Online (Sandbox Code Playgroud)

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


小智 11

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过简单的事件调用来获取您喜欢的初始化音频元素

onclick="clicksound.playclip()"

onmouseover="plopsound.playclip()"
Run Code Online (Sandbox Code Playgroud)


Lui*_*vid 7

关于什么:

$('#play').click(function() {
  const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");
  audio.play();
});
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 5

JSFiddle 演示

这是我在 jQuery 中使用的:

$('.button').on('click', function () { 
    var obj = document.createElement('audio');
    obj.src = 'linktoyourfile.wav'; 
    obj.play(); 
});
Run Code Online (Sandbox Code Playgroud)