HTML and CSS Reference
In-Depth Information
Audio Support
For audio, Emscripten provides implementations of both SDL_audio and OpenAL. If you need more direct access to
the browser's JavaScript audio APIs, there are several ways to access JavaScript from C++. One of them is embind, a
Boost.Python-like interface to JavaScript objects. embind is included with Emscripten, but requires the --bind option
passed to emcc. To illustrate how embind can be used to access browser APIs, the program in Listing 18-7 plays a two-
second tone by using embind to directly manipulate Web Audio API JavaScript objects.
Listing 18-7. Accessing the Web Audio API from C++ with embind
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <math.h>
using namespace emscripten;
const double PI = atan(1) * 4;
int main() {
val AudioContext = val::global("AudioContext");
if (!<bool>()) {
AudioContext = val::global("webkitAudioContext");
val context = AudioContext.new_();
int duration = 2;
int sampleRate = 44100;
int numberOfFrames = duration * sampleRate;
val buffer =<val>("createBuffer", 1, numberOfFrames, sampleRate);
val data =<val>("getChannelData", 0);
for (int i = 0; i < numberOfFrames; ++i) {
data.set(i, val(sin(440.0 * PI * i / sampleRate)));
auto source =<val>("createBufferSource");
source.set("buffer", buffer);<void>("connect", context["destination"]);<void>("start", 0);
There are a handful of constructs in this snippet worth calling out. The val::global function, given a string,
returns the global JavaScript value with that name. val is a C++ type defined by embind that represents a handle to a
JavaScript value.
Given a val , properties can be set with val::set and JavaScript methods can be called with val::call<ReturnVa
lue>(arguments...) .
In short, the code in Listing 18-7 is a C++ transliteration of the JavaScript in Listing 18-8.
Search WWH ::

Custom Search