Question

I can seem to figure out why my XHR response is null. My code appears to be correct from the examples I have read. I am currently initializing the script on DOM load with a listener, calling to load the audio file asynchronously, and calling a play function on buffer decode. Examining the response header shows null.. Does anyone have a clue as to why?

//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();
 }
Was it helpful?

Solution 2

I was not able to access the URL on my S3 bucket due to the same-origin policy. My solution was to load the file locally. Thank you @tavi for the error response, it helped my come to the solution.

OTHER TIPS

If you test this in Chrome 33.0.1736.2 dev you get the following error:

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. 

Here is the source: http://jsfiddle.net/dragulceo/84G7v/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top