HTML and CSS Reference
In-Depth Information
Listing 18-8. Accessing the Web Audio API from JavaScript
function main() {
var audioContext = window.AudioContext;
if (!audioContext) {
audioContext = window.webkitAudioContext;
}
var context = new audioContext();
var duration = 2;
var sampleRate = 44100;
var numberOfFrames = duration * sampleRate;
var buffer = context.createBuffer(1, numberOfFrames, sampleRate);
var data = buffer.getChannelData(0);
for (var i = 0; i < numberOfFrames; ++i) {
data[i] = Math.sin(441.0 * Math.PI * i / sampleRate);
}
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
With embind, anything you might write in JavaScript can be transliterated to C++, and thus the browser's
capabilities are exposed to your game.
Note
when compiling the program in Listing 18-8, make sure to use the --bind emcc option to enable embind support.
Input Events
Emscripten provides three ways to access user input events: SDL input, glut, and direct access to browser events.
If your application is built on SDL ( www.libsdl.org/ ) , using the SDL input events is an obvious choice. If all you need is
quick access to an OpenGL context and keyboard and mouse events, glut, the OpenGL Utility Toolkit, is also available.
Emscripten includes the open source FreeGLUT ( http://freeglut.sourceforge.net/ ) implementation.
Finally, if your game benefits from direct access to browser events, use embind to connect your C++ code to
JavaScript event callbacks such as canvas.onmousemove .
Performance
Current benchmarks show that Emscripten-compiled asm.js code is about a factor of two slower than the equivalent
native code. This is possible because most native machine operations have direct analogues in JavaScript semantics.
Remember that asm.js is restricted to JavaScript expressions that can be efficiently translated to machine code.
Memory loads and stores are represented by ArrayBuffer reads and writes. Integer addition is represented
by ((x|0)+(y|0))|0 . Unsigned integer comparison is represented by ((x>>>0) < (y>>>0)) . 32-bit integer
multiplication is represented by Math.imul(x, y) .
 
 
Search WWH ::




Custom Search