adding sound emulation in browser
This commit is contained in:
parent
a751be2e97
commit
d323995196
@ -332,13 +332,69 @@ namespace ks.rt.micro_bit {
|
||||
export function servoSetPulse(pin: Pin, micros:number) {
|
||||
}
|
||||
|
||||
module AudioContextManager {
|
||||
var _context : any; // AudioContext
|
||||
var _vco : any; //OscillatorNode;
|
||||
var _vca: any; // GainNode;
|
||||
|
||||
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 stop() {
|
||||
if (_vca) _vca.gain.value = 0;
|
||||
}
|
||||
|
||||
export function tone(frequency: number, gain: number) {
|
||||
if (frequency <= 0) return;
|
||||
var ctx = context();
|
||||
if (!ctx) return;
|
||||
|
||||
gain = Math.max(0, Math.min(1, gain));
|
||||
if (!_vco) {
|
||||
try {
|
||||
_vco = ctx.createOscillator();
|
||||
_vca = ctx.createGain();
|
||||
_vco.connect(_vca);
|
||||
_vca.connect(ctx.destination);
|
||||
_vca.gain.value = gain;
|
||||
_vco.start(0);
|
||||
} catch(e) {
|
||||
_vco = undefined;
|
||||
_vca = undefined;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_vco.frequency.value = frequency;
|
||||
_vca.gain.value = gain;
|
||||
}
|
||||
}
|
||||
|
||||
export function enablePitch(pin: Pin) {
|
||||
pin.mode = PinMode.Analog | PinMode.Output;
|
||||
}
|
||||
|
||||
export function pitch(frequency: number, ms: number) {
|
||||
let cb = getResume();
|
||||
setTimeout(() => { cb() }, ms);
|
||||
AudioContextManager.tone(frequency, 1);
|
||||
setTimeout(() => {
|
||||
if (ms > 0) AudioContextManager.stop();
|
||||
cb()
|
||||
}, ms);
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user