summaryrefslogtreecommitdiff
path: root/webaudio.js
blob: 71c1dc44a30543e94e2e08915551debda8d7216c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//creating an audio context
var context;
var audioBuffer;
window.addEventListener('load', init);    

function init()
{
    try
    {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        context=new AudioContext();
    }
    catch(e)
    {
        alert("Your browser doesn't support Web Audio API");
    }
    initAudio();
}

function initAudio(){
  console.log("audio ready");
  console.log("inside audio initialized callback");
  var url1 = "someurl"
  var url2 = "someotherurl"
  loadAndPlay(url1, function(){ 
    loadAndPlay(url2, function(){
      console.log("played both urls");
    });
  });


}
function loadAndPlay(url, callback) {
    var audioURL=url;

    //creating a new request
    var request = new XMLHttpRequest();
    request.open("GET",audioURL,true);
    request.responseType= 'arraybuffer';
    request.onload = function(){
        //take the audio from http request and decode it in an audio buffer
        context.decodeAudioData(request.response, function(buffer){
          audioBuffer = buffer;
          console.log(audioBuffer);
          if(audioBuffer){  // check here
            playSound(callback);
          }
        });

    };

    request.send();
}

//playing the audio file
function playSound(callback) {

    //creating source node
    var source = context.createBufferSource();
    //passing in file
    source.buffer = audioBuffer;
    source.onended = function(){
      console.log("inside ended callback");
      console.log("ended");
      if (typeof(callback) != "undefined" ){
        callback(); 
      }
    }
    //start playing
    source.connect(context.destination);  // added
    source.start(0);
    console.log('playing');

}