WE.mount('doppler', function (S) { var C = S.C, ctx = S.ctx, x = 0, rings = [], acc = 0, Cs = 120; var v = S.slider('Speed of the source', 0, 1.6, .5, .05, function (m) { return m === 0 ? 'Standing still' : (m * 100).toFixed(0) + '% of the speed of sound'; }); S.button('Hear it pass', function () { var m = Math.min(.9, v.v); try { var o = S.tone(440 / (1 - m), 2.2, 'sawtooth', .06); o.frequency.setValueAtTime(440 / (1 - m), o.context.currentTime); o.frequency.exponentialRampToValueAtTime(440 / (1 + m), o.context.currentTime + 1.3); } catch (e) { } }); S.loop(function (dt) { var w = S.W, h = S.H, m = v.v; x += m * Cs * dt; if (x > w + 80) { x = -80; rings = []; } acc += dt; while (acc > .22) { acc -= .22; rings.push({ x: x, r: 0 }); } rings.forEach(function (r) { r.r += Cs * dt; }); rings = rings.filter(function (r) { return r.r < w; }); S.clear(); rings.forEach(function (r) { S.ring(r.x, h / 2, r.r, 'rgba(111,177,230,' + Math.max(.08, .7 - r.r / w) + ')', 1.5); }); if (m > 1) { var a = Math.asin(1 / m), L = w; S.ln(x, h / 2, x - L * Math.cos(a), h / 2 - L * Math.sin(a), C.red, 2); S.ln(x, h / 2, x - L * Math.cos(a), h / 2 + L * Math.sin(a), C.red, 2); } S.dot(x, h / 2, 9, C.acc); S.arrow(x + 12, h / 2, x + 22 + m * 30, h / 2, C.acc, 2); var f = 440, ahead = m < 1 ? f / (1 - m) : null, behind = f / (1 + m); S.txt('Behind: ' + behind.toFixed(0) + ' Hz, lower', 14, 22, C.blue, 13.5, 'left', 600); S.txt(ahead ? 'Ahead: ' + ahead.toFixed(0) + ' Hz, higher' : 'Ahead: silence, then a boom', w - 60, 22, C.red, 13.5, 'right', 600); S.say(m === 0 ? 'A still source sends out even rings: a steady 440 Hz note in every direction.' : m < 1 ? 'The source chases its own waves. They bunch up in front, so the pitch is higher, and stretch out behind, so it is lower. That is the drop you hear as a siren passes.' : 'Faster than sound. The waves cannot get ahead, so they pile into a cone: a shock wave, heard on the ground as a sonic boom.'); }); });