Sonido en tus juegos
Sin descargar ni un solo archivo de audio: el navegador puede generar sonido con código, desde cero.
Sound in your games
Without downloading a single audio file: the browser can generate sound with code, from scratch.
Todo sonido en la web pasa por un AudioContext: es la mesa de mezcla donde
se conectan las piezas de audio. Primero se crea, y después se le conectan
osciladores —generadores de un tono puro— y controles de volumen.
Un detalle del navegador: por seguridad, el audio no puede arrancar solo al cargar la página. Tiene que empezar dentro de un clic o un toque real de la persona. Por eso este ejemplo usa un botón.
All sound on the web goes through an AudioContext: it is the mixing desk
where audio pieces connect. First you create it, then connect oscillators —
pure tone generators — and volume controls to it.
A browser detail: for security, audio cannot start on its own when the page loads. It has to begin inside a real click or tap from the person. That is why this example uses a button.
El oscilador tiene una propiedad type que cambia el timbre
del sonido: "sine" suena suave y redondo, "square" suena parecido a
un videojuego viejo, "sawtooth" suena áspero, y "triangle" queda en
el medio.
The oscillator has a type property that changes the timbre
of the sound: "sine" sounds smooth and round, "square" sounds like
an old video game, "sawtooth" sounds harsh, and "triangle" sits in
between.
Un efecto de videojuego casi nunca es un solo tono fijo: normalmente sube o baja
de frecuencia en el trayecto. Eso se hace con
frequency.exponentialRampToValueAtTime() — "ve deslizando la frecuencia hasta
este valor, en este tiempo".
A game sound effect is almost never a single fixed tone: it usually
slides up or down along the way. That is done with
frequency.exponentialRampToValueAtTime() — "glide the frequency to this value,
over this time".
Con lo que sabes de setTimeout —o mejor, encadenando tiempos— puedes tocar
varias notas seguidas. Una lista de notas más un bucle, otra vez.
With what you know about setTimeout — or better, chaining times — you can
play several notes in a row. A list of notes plus a loop, once again.
AudioContext, osciladores y volumen, distintas formas de onda, deslizar la
frecuencia para efectos de acierto y error, y encadenar notas para una melodía simple.
Nuestros cuatro juegos usan exactamente esta técnica para sus efectos — cero archivos de audio, todo generado con código.
AudioContext, oscillators and volume, different waveforms, sliding frequency
for hit and miss effects, and chaining notes into a simple melody.
Our four games use exactly this technique for their effects — zero audio files, all generated with code.