-
Notifications
You must be signed in to change notification settings - Fork 0
/
wavePlayer.js
106 lines (92 loc) · 2.35 KB
/
wavePlayer.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
var portAudio = require('portaudio');
module.exports.play = function(note, octave, waveType)
{
const factor = Math.pow(2, (1/12));
var sampleRate = 44100;
var baseFreq = 440;
var baseOctave = 4;
var NOTES = {
'a' : 0,
'a#': 1,
'b' : 2,
'c' : 3,
'c#': 4,
'd' : 5,
'd#': 6,
'e' : 7,
'f' : 8,
'f#': 9,
'g' : 10,
'g#': 11
};
var semitonesFromBase = (octave - baseOctave) * 12 + NOTES[note];
var tableSize = sampleRate/(baseFreq*Math.pow(factor,semitonesFromBase));
var buffer;
switch(waveType) {
case 'sine':
buffer = createSineWave(tableSize);
break;
case 'saw':
buffer = createSawWave(tableSize);
break;
case 'square':
buffer = createSquareWave(tableSize);
case 'random':
buffer = createRandomWave(tableSize);
}
var audioObj;
portAudio.open({
channelCount: 1,
sampleFormat: portAudio.SampleFormat8Bit,
sampleRate: sampleRate
}, function (err, pa) {
audioObj = pa;
// send samples to be played
for (var i = 0; i < 5 * sampleRate / tableSize; i++) {
pa.write(buffer);
}
// start playing
pa.start();
});
return audioObj;
};
module.exports.stop = function(audioObj)
{
audioObj.stop();
};
var createSineWave = function(tableSize)
{
var buffer = new Buffer(tableSize);
for (var i = 0; i < tableSize; i+= 1) {
buffer[i] = (Math.sin((i / tableSize) * 3.1415927 * 2.0) * 127);
}
return buffer;
};
var createSawWave = function(tableSize)
{
var buffer = new Buffer(tableSize);
for (var i = 0; i < tableSize; i+= 1) {
buffer[i] = -128 + (256*i / (tableSize - 1));
}
return buffer;
};
var createSquareWave = function(tableSize)
{
var buffer = new Buffer(tableSize);
var halfwayPoint = Math.floor(tableSize / 2);
for (var i = 0; i < halfwayPoint; i+= 1) {
buffer[i] = 127;
}
for (var i = halfwayPoint; i < tableSize; i += 1) {
buffer[i] = -128;
}
return buffer;
};
var createRandomWave = function(tableSize)
{
var buffer = new Buffer(tableSize);
for (var i = 0; i < tableSize; i+= 1) {
buffer[i] = 256*Math.random() - 128;
}
return buffer;
};