【发布时间】:2014-07-12 04:01:07
【问题描述】:
我用 JS 和 HTML5 定制了一个音频播放器。 首先,我做的很简单:
<div id="btnPlayPause" playing="" state=""></div>
<audio style="display:none;" id="realSounder" preload="meta">
<source src="" type="audio/mpeg">
</audio>
还有 JS:
$("#btnPlayPause").click(function(){
realSounder = document.getElementById('realSounder');
realSounder.src = "http://domain.com/aloha.mp3";
realSounder.play();
});
运行良好。但是当我用 UI 控件实现时,需要更复杂的代码:
function initPlayer () {
realSounder = document.getElementById('realSounder');
realSounder.volume = 0.8;
subscribe('canplay', realSounder, function() {
if (realSounder.getAttribute('state') != 'playing')
realSounder.play();
});
subscribe('canplaythrough', realSounder, function() {
if (realSounder.getAttribute('state') != 'playing')
realSounder.play();
});
}
function subscribe(event, element, func) {
//addEventListener for cross-browser.
if (element.addEventListener) {
element.addEventListener(event, func, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, func);
} else {
element['on' + event] = func;
}
}
$(document).ready(function() {
initPlayer();
$("#btnPlayPause").click(function(e) {
e.preventDefault();
//do something for display
play();
});
});
function play() {
var loadUrl = "/wap.php/AjaxLoadAudio";
var audioId = $("#btnPlayPause").attr('playing'); //get id of audio
$.getJSON(
loadUrl,
{audio_id:audioId},
function(json){
realSounder.src = json.audio_share_url;
}
).error(function() {
console.log('Error: 404');
});
}
它不起作用。似乎realSounder 无法引发事件canplay 或canplaythrough 来播放声音。为什么?我尝试在 canplay 和 canplaythrough 的处理程序函数中使用 console.log() 或 alert() 但什么也没发生!
注意:
我已经测试了这段代码并且成功:
- IE11/Windows Phone 8.1
- Android 浏览器/Android 4.1,4.3
然后失败:
- Safari / iPhone 4、4S
- Firefox、Chrome / Android 4.1、4.3
【问题讨论】:
-
所以,这和'canplay'无关?在我看来,这里的问题更多地与用户交互和对“play()”的调用之间存在脱节有关 - 即点击 -> ajax ==/== canplay -> play()。这个问题的标题有没有可能改变?
标签: javascript html html5-audio