我似乎可以弄清楚为什么我的XHR响应为空。从我读过的例子来看,我的代码似乎是正确的。我目前正在使用侦听器初始化DOM加载脚本,调用异步加载音频文件,并在缓冲区解码时调用播放函数。检查响应标题显示null ..有没有人知道为什么?
//ON DOM LOAD INITIALIZE AUDIO
window.addEventListener('load', init, false); // On Window Load Initialize
//GLOBAL VARS
var context;
var myAudioBuffer = null;
var source = null;
//INITIALIZE
function init() {
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
loadSound("https://s3.amazonaws.com/PersonalWebServerContent/Projects/PalmDesert/Audio/sunshine.mp3");//Load Audio Track
}
catch(e) {
alert('Sorry, your browser does not support the Web Audio API.');
}
}
//LOAD SOUND SOURCE
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
myAudioBuffer = buffer;
playSound(myAudioBuffer);//Play Audio Track
});
}
request.send();
}
//PLAY SOUND BUFFER
function playSound(buffer) {
source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start();
}
答案 0 :(得分:1)
如果您在Chrome 33.0.1736.2 dev中进行测试,则会出现以下错误:
XMLHttpRequest cannot load https://s3.amazonaws.com/PersonalWebServerContent/Projects/PalmDesert/Audio/sunshine.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
答案 1 :(得分:0)
由于同源策略,我无法访问S3存储桶上的URL。我的解决方案是在本地加载文件。感谢@tavi的错误响应,它帮助我找到了解决方案。