forked from gattis/milkshake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTML5Audio.js
90 lines (72 loc) · 2.4 KB
/
HTML5Audio.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var HTML5Audio = Class.extend({
init: function () {
this.context = null;
this.source = null;
if (typeof webkitAudioContext != "undefined")
this.audioAPI = new WebkitHTML5Audio();
else
this.audioAPI = new MozAudioAPI();
}
});
var WebkitAudioAPI = Class.extend({
init: function() {
this.context = new webkitAudioContext();
this.source = context.createBufferSource();
this.processor = context.createJavaScriptNode(512);
this.processor.onaudioprocess = this.audioAvailable;
this.source.connect(processor);
this.processor.connect(context.destination);
this.loadSample("song.ogg");
},
loadSample: function(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
this.context.decodeAudioData(request.response, function(buffer) {
this.source.buffer = buffer;
this.source.looping = true;
this.source.noteOn(0);
});
}
request.send();
},
audioAvailable: function(event) {
var inputArrayL = event.inputBuffer.getChannelData(0);
var inputArrayR = event.inputBuffer.getChannelData(1);
var outputArrayL = event.outputBuffer.getChannelData(0);
var outputArrayR = event.outputBuffer.getChannelData(1);
var n = inputArrayL.length;
for (var i = 0; i < n; ++i) {
outputArrayL[i] = inputArrayL[i];
outputArrayR[i] = inputArrayR[i];
}
if (typeof shaker != "undefined")
shaker.music.addPCM(inputArrayL, inputArrayR);
}
});
var MozAudioAPI = Class.extend({
init: function() {
this.context = new Audio();
this.context.src = "song.ogg";
this.context.addEventListener('MozAudioAvailable', this.audioAvailable);
this.context.addEventListener('loadedmetadata', this.loadedMetadata, false);
this.context.play();
},
loadedMetadata: function () {
this.channels = this.context.mozChannels;
this.rate = this.context.mozSampleRate;
this.frameBufferLength = this.context.mozFrameBufferLength;
},
audioAvailable: function (event) {
var fb = event.frameBuffer;
var signalL = new Float32Array(fb.length / 2);
var signalR = new Float32Array(fb.length / 2);
for (var i = 0; i < this.frameBufferLength / 2; i++) {
signalL[i] = fb[2*i];
signalR[i] = fb[2*i+1];
}
if (typeof shaker != "undefined")
shaker.music.addPCM(signalL, signalR);
}
});