单击按钮时使用jQuery播放音频文件 [英] Play an audio file using jQuery when a button is clicked

查看:188
本文介绍了单击按钮时使用jQuery播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < HTML> 
< body>
< div id =container>
< button id =play>
播放音乐
< /按钮>
< / 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();
});
});
});

我创建了 Fiddle 也是这样。

您可以使用< audio> 标签或< object> < embed>
懒惰加载(当你需要时加载)如果它的尺寸很小,声音是最好的方法。你可以动态地创建音频元素,当它被加载时,你可以用 .play()来启动它,并用 .pause()

我们用过的东西



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

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



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



示例指南




  1. 当文档准备就绪时,我们动态创建了一个音频元素
  2. 我们使用我们想播放的音频设置它的源代码。

  3. 我们使用已结束事件再次启动文件。




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




  1. 每当音频 .currentTime 时,我们使用 timeupdate 事件更新当前时间。
  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( ();}();}();}();}();}()点击(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>< /脚本><身体GT; < h2>声音信息< / h2> < div id =length>持续时间:< / div> < div id =source>来源:< / div> < div id =statusstyle =color:red;>状态:正在载入< / div> < HR> < h2>控制按钮< / h2> < button id =play>播放< / button> < button id =pause>暂停< /按钮> < button id =restart>重新启动< / button> < HR> < h2>播放信息< / h2> < div id =currentTime> 0< / div>< / body>  

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

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

my JavaScript is :

$('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 Fiddle for that too.

解决方案

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().

Things we used

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

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.

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.

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.

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

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

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

这篇关于单击按钮时使用jQuery播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆