简体   繁体   中英

Google Closure Compiler - How to set externs?

How do I set up closure compiler annotation / externs to compile the following properly?

var ac, volumeNode;
var load_sound = true;
var contextClass = (window.AudioContext || 
        window.webkitAudioContext || 
        window.mozAudioContext || 
        window.oAudioContext || 
        window.msAudioContext);
if (contextClass) {
    ac = new contextClass();
    volumeNode = ac.createGain();
    volumeNode.connect(ac.destination);
} else {
    load_sound = false;
}

Currently it renames createGain, destination, window.AudioContext, and so on.

I know I can use ["properly"] syntax to access everything, but that will create a lot of mess in my code. Is there a simpler way?

Update: The w3c_audio.js externs have been moved to the default externs for the compiler. With the next release (releases newer than 20150315), the externs will be automatically included.

If you need to manually reference the externs, you'll find them in the main externs folder: https://github.com/google/closure-compiler/blob/master/externs/browser/w3c_audio.js

For those who come to this page looking for a working example, I've got this jsFiddle setup with code that works and that compiles in GCC:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @externs_url https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jquery-1.9.js
// @externs_url https://raw.githubusercontent.com/tambien/AudioJS/master/compiler/externs/w3c_audio.js
// ==/ClosureCompiler==

var DialPadContext;
var Oscillator1;

function Start() {

    $('.Key').mousedown(function () {
        PlayTone($(this).text());
    });

    $('.Key').mouseup(function () {
        if (Oscillator1 && Oscillator1.disconnect) {
            Oscillator1.disconnect();
        }
    });

    DialPadContext = new window.AudioContext();
}

function PlayTone(TheKeyValue) {

    var TonesFrequencies = {

            '0': [941.0, 1336.0],
            '1': [697.0, 1209.0],
            '2': [697.0, 1336.0],
            '3': [697.0, 1477.0],
            '4': [770.0, 1209.0],
            '5': [770.0, 1336.0],
            '6': [770.0, 1477.0],
            '7': [852.0, 1209.0],
            '8': [852.0, 1336.0],
            '9': [852.0, 1477.0],
            '*': [941.0, 1209.0],
            '#': [941.0, 1477.0]
    }

    Oscillator1 = DialPadContext.createOscillator();
    Oscillator1.frequency.value = TonesFrequencies[TheKeyValue][0];

    var gainNode = DialPadContext['createGain']();

    Oscillator1.connect(gainNode, 0, 0);
    gainNode.connect(DialPadContext.destination);
    gainNode.gain.value = .1;
    Oscillator1.start(0);
}

$(Start);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM