我尝试了很多不同的方法来让 JavaScript 计时器在平板电脑上响一次。我使用了以下函数/调用:
$('#play-button').click(function(){ audio.play(); });}
这段代码在html中
<audio id="audiotag1" preload="auto" controls="false" autoplay="autoplay">
<source src="buzz.mp3" />
</audio>
它在 Windows 7 操作系统上运行良好,但在手机上则不然。 欢迎使用其他方法,还是根本不可能?
最佳答案
您的问题之前已被问过
哪种方法?
您可以使用 <audio>
播放音频标签或 <object>
或<embed>
。
延迟加载(需要时加载)如果声音尺寸较小,则这是最好的方法。您可以动态创建音频元素,加载后您可以使用 .play()
启动它并用 .pause()
暂停它.
我们使用过的东西
我们将使用canplay
检测我们的文件已准备好播放的事件。
没有.stop()
音频元素的函数。我们只能暂停他们。当我们想从音频文件的开头开始时,我们更改它的 .currentTime
。我们将在示例中使用此行 audioElement.currentTime = 0;
。实现.stop()
函数中我们首先暂停文件,然后重置其时间。
我们可能想知道音频文件的长度和当前的播放时间。我们已经了解到.currentTime
上面,为了了解它的长度,我们使用 .duration
.
示例指南
- 文档准备好后,我们动态创建了一个音频元素
- 我们使用要播放的音频设置其来源。
- 我们使用“结束”事件再次开始文件。
When the currentTime is equal to its duration audio file will stop playing. Whenever you use
play()
, it will start from the beginning.
- 我们使用了
timeupdate
每当有音频.currentTime
时更新当前时间的事件变化。 - 我们使用了
canplay
文件准备好播放时更新信息的事件。 - 我们创建了播放、暂停、重新启动的按钮。
$(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>
关于javascript - 使用 JavaScript 在 Android (Chrome) 上使用计时器播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40956266/