使用 JavaScript 在 Android (Chrome) 上使用计时器播放声音

Play sound using timer on Android (Chrome) using JavaScript

我尝试了很多不同的方法来让 javascript 计时器在平板电脑上响起一次。我使用了以下 functions/calls:

$('#play-button').click(function(){ audio.play(); });}

以及 html

中的代码
<audio id="audiotag1" preload="auto" controls="false" autoplay="autoplay">
   <source src="buzz.mp3" />
</audio>

它在 windows 7 OS 上运行良好,但在手机上运行不佳。 欢迎任何其他方法,还是不可能?

你的问题之前有人问过

哪种方法?

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

暂停它

我们用过的东西

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

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

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

示例指南

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

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

  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>