重用HTML5音频对象在移动Safari浏览器 [英] Reusing HTML5 Audio Object in Mobile Safari

查看:143
本文介绍了重用HTML5音频对象在移动Safari浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在响应用户输入与事件和音频播放之间最小的延迟在iPad上的移动Safari浏览器上运行我的web应用程序,以发挥短(少于1秒)的音频文件。回放可以多次触发页面重载的,所以我要缓存的音频文件。

I want to play a short (less than 1s) audio file in response to user input on my web app running in Mobile Safari on the iPad with minimum latency between event and audio playback. The playback can be triggered multiple times between page reloads, therefore I want to cache the audio file.

下面就扮演着第一次点击该文件,但不是之后什么也没有发生:

The following plays the file on the first click but after than nothing happens:

var audio = new Audio("ack.mp3");
$("#button").click(function(e) {
  e.preventDefault();
  audio.play();
}

如果我添加事件侦听器的端​​事件,重新加载,我可以得到来自同一物体的两个播放和文件,然后沉默了:

If I add an event listener to the "ended" event which reloads the file I can get two playbacks from the same object and then silence:

var audio = new Audio("ack.mp3");
audio.addEventListener('ended', function() {
  audio.load();
}, false);
$("#button").click(function(e) {
  e.preventDefault();
  audio.play();
}

如果我手动设置currentTime的属性为0,这样的:

If I manually set the currentTime attribute to 0 like this:

var audio = new Audio("ack.mp3");
audio.addEventListener('ended', function() {
  audio.currentTime=0;
}, false);
$("#button").click(function(e) {
  e.preventDefault();
  audio.play();
}

我得到了错误控制台以下错误:

I get the following error in the error console:

INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.

如何使这项工作任何想法?在此先感谢

Any ideas on how to make this work? Thanks in advance

推荐答案

设置 currentTime的 0.1 而不是零不要使用负荷()否则会打破结束事件。

set currentTime to 0.1 instead of zero, don't use load() otherwise it will break the ended event.

如果您需要preLOAD媒体文件使用:

if you need to preload the media file use:

media.play(); //start loading
if(media.readyState !== 4){ //HAVE_ENOUGH_DATA
  media.addEventListener('canplaythrough', onCanPlay, false);
  media.addEventListener('load', onCanPlay, false); //add load event as well to avoid errors, sometimes 'canplaythrough' won't dispatch.
  setTimeout(function(){
    media.pause(); //block play so it buffers before playing
  }, 1); //it needs to be after a delay, otherwise it will block download and/or won't pause.
}else{
  onCanPlay();
}

这篇关于重用HTML5音频对象在移动Safari浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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