-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathaudioUtil.ts
81 lines (66 loc) · 2.09 KB
/
audioUtil.ts
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
namespace pxt.AudioContextManager {
let _frequency = 0;
let _context: AudioContext; // AudioContext
let _vco: OscillatorNode; // OscillatorNode;
let _gain: GainNode;
let _mute = false; //mute audio
function context(): any {
if (!_context) _context = freshContext();
return _context;
}
function freshContext(): any {
(<any>window).AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
if ((<any>window).AudioContext) {
try {
// this call my crash.
// SyntaxError: audio resources unavailable for AudioContext construction
return new (<any>window).AudioContext();
} catch (e) { }
}
return undefined;
}
export function mute(mute: boolean) {
if (!_context)
return;
_mute = mute;
stop();
if (mute && _vco) {
_vco.disconnect();
_gain.disconnect();
_vco = undefined;
_gain = undefined;
}
}
export function stop() {
if (!_context)
return;
_gain.gain.setTargetAtTime(0, _context.currentTime, 0.015);
_frequency = 0;
}
export function frequency(): number {
return _frequency;
}
export function tone(frequency: number) {
if (_mute) return;
if (isNaN(frequency) || frequency < 0) return;
_frequency = frequency;
let ctx = context() as AudioContext;
if (!ctx) return;
try {
if (!_vco) {
_vco = ctx.createOscillator();
_vco.type = 'triangle';
_gain = ctx.createGain();
_gain.gain.value = 0;
_gain.connect(ctx.destination);
_vco.connect(_gain);
_vco.start(0);
}
_vco.frequency.linearRampToValueAtTime(frequency, _context.currentTime)
_gain.gain.setTargetAtTime(.2, _context.currentTime, 0.015);
} catch (e) {
_vco = undefined;
return;
}
}
}