单击按钮时播放音频文件

问题描述 投票:0回答:7
javascript jquery html
7个回答
173
投票

哪种方法?

您可以使用

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

我们用过的东西

我们将使用

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

音频元素没有

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

我们可能想知道音频文件的长度和当前播放的时间。我们已经在上面学习了

.currentTime
,为了了解它的长度,我们使用
.duration

示例指南

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

当当前时间等于其持续时间时,音频文件将停止 玩。每当您使用

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>


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

它不能像您期望的那样与

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

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

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


24
投票

对于其他跟随的人,我只是简单地采用了 Ahmet 的答案并更新了原始提问者的 jsfiddle ,替换为:

audio.mp3

对于

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

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


14
投票

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

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

13
投票

关于:

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

5
投票

JSFiddle 演示

这就是我使用 jQuery 的方法:

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

-1
投票
// Simple Function
function playSound(audioSource) { //
    var audio = new Audio(audioSource);
    audio.play();
  }

// To play sound 
playSound(audioSource)

 // audiouSource is the path of the sound & is a string. (E.g "./sound/dog.mp3")
© www.soinside.com 2019 - 2024. All rights reserved.