-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
205 lines (184 loc) · 6.76 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
(function() {
'use strict';
let start = document.querySelector('button[start]');
let stop = document.querySelector('button[stop]');
let frameSpan = document.querySelector('div[frame]');
let status = document.querySelector('span[status]');
let canvas = document.querySelector('canvas');
let select = document.querySelector('select[song]');
let glCtx = canvas.getContext('2d');
function $get(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('progress', (e) => {
status.innerText = `Loading media ${(100 * e.loaded / e.total).toFixed(3)}% ...`;
});
xhr.onreadystatechange = () => {
switch(xhr.readyState) {
case xhr.DONE:
resolve(xhr.response)
break;
default:
break;
}
};
xhr.send();
});
}
class Wav {
constructor(file) {
let rawFile = file;
file = new Uint8Array(rawFile);
// Reference for RIFF chunk and FMT chunk
let RIFF = {
RIFF: { begin: 0, length: 4, type: 'CHAR'},
ChunkSize: { begin: 4, length: 4, type: 'INTEGER'},
WAVE: { begin: 8, length: 4, type: 'CHAR'},
}
let FMT = {
fmt: { begin: 12, length: 4, type: 'CHAR'},
Subchunk1Size: { begin: 16, length: 2, type: 'INTEGER'},
AudioFormat: { begin: 20, length: 2, type: 'INTEGER'},
NumOfChan: { begin: 22, length: 2, type: 'INTEGER'},
SamplesPerSec: { begin: 24, length: 4, type: 'INTEGER'},
bytesPerSec: { begin: 28, length: 4, type: 'INTEGER'},
blockAlign: { begin: 32, length: 2, type: 'INTEGER'},
bitsPerSample: { begin: 34, length: 2, type: 'INTEGER'},
}
file.subArray = (begin, length) => {
return file.slice(begin, begin + length);
};
let readChar = (begin, length) => Array
.from(file
.subArray(begin, length))
.map(ch => String.fromCharCode(ch))
.join('');
let readInt = (begin, length) => Array
.from(file
.subArray(begin, length))
.reverse()
.reduce((a, b) => a * 256 + b);
let readChunk = (ref, save) => {
for (let item in ref) {
switch(ref[item].type) {
case 'CHAR':
save[item] = readChar(ref[item].begin, ref[item].length);
break;
case 'INTEGER':
save[item] = readInt(ref[item].begin, ref[item].length);
break;
}
}
}
// Read the RIFF chunk
readChunk(RIFF, this);
// Keep reading data until finding the 'data' chunk
for (let offset = 12;;) {
let chunkName = readChar(offset, 4); offset += 4;
let chunkSize = readInt(offset, 4); offset += 4;
this[chunkName] = {};
this[chunkName].size = chunkSize;
if (chunkName === 'fmt ') {
// Read the RIFF chunk
readChunk(FMT, this[chunkName]);
}
else {
if (chunkName == 'data') {
let type = `Int${this['fmt '].bitsPerSample}Array`;
this[chunkName] = new window[type](rawFile.slice(offset, chunkSize))
break;
}
// Read as raw
this[chunkName]._rawData = file.subArray(offset, chunkSize);
}
offset += chunkSize;
}
}
prepare() {
let ctx, framesCount;
try {
ctx = this.ctx = new (window.AudioContext || window.webkitAudioContext)();
framesCount = this.framesCount = wav.ChunkSize / (wav['fmt '].bitsPerSample / 8);
} catch (ex) {
alert('browser do not support AudioContext API');
return
}
let audioBuffer = this.audioBuffer = ctx.createBuffer(
wav['fmt '].NumOfChan,
framesCount / 2,
wav['fmt '].SamplesPerSec
);
this.source = ctx.createBufferSource();
this.source.loop = false;
this.source.connect(ctx.destination);
this.source.buffer = this.audioBuffer;
let last500frames = this.last500frames = new Array(500).fill(0);
this.sampleingInterval = 16;
}
*step() {
let ctx = this.ctx;
let channelBuffering = [];
for (let i = 0; i < wav['fmt '].NumOfChan; ++i) {
channelBuffering[i] = this.audioBuffer.getChannelData(i);
}
for (let currentFrame = 0; currentFrame < this.framesCount; ++currentFrame) {
channelBuffering[currentFrame % 2][Math.ceil(currentFrame / 2)]
= Number(wav.data[currentFrame]) / (1 << (wav['fmt '].bitsPerSample - 1));
if (currentFrame % (this.sampleingInterval * 2) === 1) {
this.last500frames.shift();
this.last500frames.push((channelBuffering[1][Math.ceil(currentFrame / 2)] + channelBuffering[0][Math.ceil(currentFrame / 2)]) / 2);
}
if (!this.started) {
setTimeout(() => {this.source.start()}, 10);
this.started = true;
}
yield currentFrame;
}
}
}
function main() {
$get(select.value).then((file) => {
status.innerText = 'Loading media ... ';
start.style.display = 'none';
window.wav = new Wav(file);
status.innerText = 'Playing ... ';
wav.prepare();
let begin = new Date();
let iterator = wav.step();
window.intervalId = setInterval(() => {
let diff = new Date().getTime() - begin.getTime();
let last;
for (;;) {
last = iterator.next().value;
if (typeof last === 'undefined') {
clearInterval(window.intervalId);
start.style.display = '';
status.innerText = 'Ready ... ';
console.info('end');
break;
}
diff = new Date().getTime() - begin.getTime() + 10;
if (last / wav['fmt '].SamplesPerSec / wav['fmt '].NumOfChan > diff / 1000) break;
}
frameSpan.innerText
= `Current Frame Index: ${last}\n`
+ `Time Offset(Frame): ${last / wav['fmt '].SamplesPerSec / wav['fmt '].NumOfChan}\n`
+ `Time Offset(Clock): ${diff / 1000}\n`
+ `Buffered / Played: ${last / ((new Date().getTime() - begin.getTime()) / 1000 * wav['fmt '].SamplesPerSec * wav['fmt '].NumOfChan)}`;
// Draw the visualizer.
let width = canvas.width;
let height = canvas.height;
glCtx.clearRect(0, 0, width, height);
glCtx.beginPath();
glCtx.moveTo(0, canvas.height / 2);
for (let i = 0; i < 500; ++i) {
glCtx.lineTo(i * canvas.width / 500, canvas.height / 2 * (wav.last500frames[i] + 1) );
}
glCtx.stroke();
}, 10);
});
}
start.onclick = main;
})()