-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb-audio-api-player.js
85 lines (79 loc) · 1.96 KB
/
web-audio-api-player.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
var GHOST_NOTE_VOLUME = 0.2;
function WebAudioApiPlayer()
{
var context = new AudioContext();;
var buffers = [];
var sources = [];
this.updateSounds = function()
{
for(var type in mainSheet.score.noteTypes)
{
var path = mainSheet.score.noteTypes[type];
this.loadSound(type, path);
}
}
this.loadSound = function(index, path)
{
var request = new XMLHttpRequest();
request.open('GET', path, true);
request.responseType = 'arraybuffer';
request.onload = function()
{
context.decodeAudioData(
request.response,
function(buffer) {buffers[index] = buffer;});
}
request.send();
}
this.play = function()
{
for(var note of mainSheet.score.notes)
{
if(note.time >= startBeat - 1 && note.time < endBeat &&
!note.muted)
{
this.playNote(note);
}
}
}
this.playNote = function(note, playNow)
{
var buffer = buffers[note.type];
if(playNow)
{
var delay = null;
}
else
{
var delay = toSeconds(note.time - (startBeat - 1));
}
var source = context.createBufferSource();
source.buffer = buffer;
if(note.ghost)
{
var gainNode = context.createGain();
gainNode.gain.value = GHOST_NOTE_VOLUME;
source.connect(gainNode);
gainNode.connect(context.destination);
}
else
{
source.connect(context.destination);
}
var time = context.currentTime;
if(delay != null)
{
time += delay;
}
source.start(time);
sources.push(source);
}
this.stop = function()
{
for(var source of sources)
{
source.stop();
}
sources = [];
}
}