Este artigo necessita de uma revisão técnica. Como posso ajudar.
Este artigo necessita de uma revisão editorial. Como posso ajudar.
Esta tradução está incompleta. Ajude atraduzir este artigo.
A API de Web Audio disponibiliza um poderoso e versátil sistema de controle de áudio para a Web, permitindo aos desenvolvedores escolher arquivos de áudio, adicionar efeitos a estes arquivos, criar reprodutores de áudio, aplicar spatial effects (como panning) e muito mais.
Web audio: conceitos e uso
A API de Web audio envolve manipulação de operações com áudio dentro de um contexto de áudio, e foi desenvolvida para permitir o roteamento modular. Operações básicas de áudio são feitas com audio nodes (nós de áudio), que são ligados para formar gráficos de roteamento de áudio. Várias fontes - com diferentes tipos de layout de canal - são suportados mesmo em um único contexto. Este design modular permite flexibilidade para criar funções de áudio complexas com efeitos dinâmicos.
Audio nodes são ligados pelas suas entradas e saídas, formando uma cadeia que começa com uma ou mais fontes, passa por um ou mais nodes e então acaba em um destino (embora você não tenha que fornecer um destino, por exemplo, se você quiser apenas visualizar alguns dados de áudio). Um fluxo de trabalho simples, com Web áudio, seria algo parecido com isso:
- Crie um contexto de áudio
- Dentro do contexto, crie fontes de áudio — como
<audio>, oscilador, stream - Crie efeitos de áudio, como reverb, biquad filter, panner, compressor
- Escolha o destino final de áudio, por exemplo os auto-falantes de seu sistema
- Conecte as fontes de áudio com os efeitos, e os efeitos com o destino.

O sincronismo é controlado com alta precisão e baixa latência, permitindo aos desenvolvedores escrever códigos que respondam com precisão a eventos e capazes de gerar exemplos específicos, mesmo com uma alta taxa de amostragem. Dessa forma, aplicações como baterias eletrônicas e seqüenciadores estarão facilmente ao alcance dos desenvolvedores.
A API de Web Audio também permite o controle de como o áudio será ordenado. Usando um sistema baseado em um modelo de source-listener, a API permite controlar os painéis de modelo para serem usados e tratados com atenuação de distância induzida ou doppler shift induzido por uma fonte em movimento (ou um ouvinte em movimento).
Nota: Você pode ver mais detalhes sobre a teoria da API de Web Audio em nosso artigo Basic concepts behind Web Audio API.
Web Audio: Interfaces da API
A API de Web Audio possui um total de 28 interfaces e eventos associados, que nós dividimos e categorizamos em 9 funcionalidades.
Definições gerais de gráficos de áudio (audio graph)
Definições gerais que moldam os gráficos de áudio no uso da API de Web Audio.
AudioContext- A interface
AudioContextrepresenta um gráfico de processamento de áudio construído a partir de módulos de áudio ligados entre si, cada um representado por umAudioNode. Um contexto de áudio (audio context) controla a criação dos nodes que ele contém e a execução do processamento de áudio, ou a decodificação. Como tudo acontece dentro de um contexto, você deve criar umAudioContextantes de fazer qualquer outra coisa. AudioNode- A interface
AudioNoderepresenta um módulo de processamento de áudio como uma fonte de áudio (por exemplo, um HTML<áudio>ou um elemento<vídeo>), destino de áudio, módulo de processamento intermediário (por exemplo, um filtro comoBiquadFilterNode, ou controle de volume, comoGainNode). AudioParam- A interface
AudioParamrepresenta um parâmetro relacionado ao áudio, como um parâmetro de umAudioNode. Ele pode ser configurado com um valor específico ou uma mudança de valor, e pode ser programado para "acontecer" em um momento específico e seguindo um padrão específico. ended(event)- O evento
endedé disparado quando a reprodução parou porque o fim da mídia foi atingido.
Definindo fontes de áudio
Interfaces que definem fontes de áudio para uso na API de Web Audio.
OscillatorNode- A interface
OscillatorNoderepresenta uma onda senoidal. Esta interface é um módulo de processamento de áudio que gera uma onda senoidal com determinada frequência. AudioBuffer- A interface
AudioBufferepresenta uma pequena porção de áudio armazenada na memória, criada a partir de um arquivo de áudio pelo métodoAudioContext.createBuffer - The
AudioBufferinterface represents a short audio asset residing in memory, created from an audio file using theAudioContext.createBuffermethod. Uma vez decodificado neste formato o áudio pode ser colocada em umAudioBufferSourceNode. AudioBufferSourceNode- The
AudioBufferSourceNodeinterface represents an audio source consisting of in-memory audio data, stored in anAudioBuffer. It is anAudioNodethat acts as an audio source. MediaElementAudioSourceNode- The
MediaElementAudioSourceNodeinterface represents an audio source consisting of an HTML5<audio>or<video>element. It is anAudioNodethat acts as an audio source. MediaStreamAudioSourceNode- The
MediaStreamAudioSourceNodeinterface represents an audio source consisting of a WebRTCMediaStream(such as a webcam or microphone.) It is anAudioNodethat acts as an audio source.
Definindo filtros de efeitos de áudio
Interfaces para definição de efeitos que você deseja aplicar em suas fontes de áudio.
BiquadFilterNode- The
BiquadFilterNodeinterface represents a simple low-order filter. It is anAudioNodethat can represent different kinds of filters, tone control devices or graphic equalizers. ABiquadFilterNodealways has exactly one input and one output. ConvolverNode- The
ConvolverNodeinterface is anAudioNodethat performs a Linear Convolution on a given AudioBuffer, often used to achieve a reverb effect. DelayNode- The
DelayNodeinterface represents a delay-line; anAudioNodeaudio-processing module that causes a delay between the arrival of an input data and its propagation to the output. DynamicsCompressorNode- The
DynamicsCompressorNodeinterface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. GainNode- The
GainNodeinterface represents a change in volume. It is anAudioNodeaudio-processing module that causes a given gain to be applied to the input data before its propagation to the output. WaveShaperNode- The
WaveShaperNodeinterface represents a non-linear distorter. It is anAudioNodethat use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal. PeriodicWave- Used to define a periodic waveform that can be used to shape the output of an
OscillatorNode.
Definindo destinos de áudio
Uma vez que você tenha feito o processamento do seu áudio, estas interfaces definirão aonde será a saída do áudio.
AudioDestinationNode- The
AudioDestinationNodeinterface represents the end destination of an audio source in a given context — usually the speakers of your device. MediaStreamAudioDestinationNode- The
MediaElementAudioSourceNodeinterface represents an audio destination consisting of a WebRTCMediaStreamwith a singleAudioMediaStreamTrack, which can be used in a similar way to a MediaStream obtained fromNavigator.getUserMedia. It is anAudioNodethat acts as an audio destination.
Análise dos dados e visualização
Se você deseja extrair tempo, frequencia e outras informações do seu áudio, o AnalyserNode é o que você necessita.
AnalyserNode- The
AnalyserNodeinterface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.
Dividindo e mesclando canais de áudio
Para dividir e mesclar canais de áudio, você utilizará essas interfaces.
ChannelSplitterNode- The
ChannelSplitterNodeinterface separates the different channels of an audio source out into a set of mono outputs. ChannelMergerNode- The
ChannelMergerNodeinterface reunites different mono inputs into a single outputs. Each input will be used to fill a channel of the output.
Audio spatialization
These interfaces allow you to add audio spatialization panning effects to your audio sources.
AudioListener- The
AudioListenerinterface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization. PannerNode- The
PannerNodeinterface represents the behavior of a signal in space. It is anAudioNodeaudio-processing module describing its position with right-hand Cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.
Processamento de áudio por JavaScript
Se você quiser usar um script externo para processar sua fonte de áudio, Node e eventos abaixo tornarão isto possível.
ScriptProcessorNode- The
ScriptProcessorNodeinterface allows the generation, processing, or analyzing of audio using JavaScript. It is anAudioNodeaudio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing theAudioProcessingEventinterface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data. audioprocess(event)- The
audioprocessevent is fired when an input buffer of a Web Audio APIScriptProcessorNodeis ready to be processed. AudioProcessingEvent- The Web Audio API
AudioProcessingEventrepresents events that occur when aScriptProcessorNodeinput buffer is ready to be processed.
Áudio offline
Manipular áudio offline é possível com estas interfaces.
OfflineAudioContext- The
OfflineAudioContextinterface is anAudioContextinterface representing an audio-processing graph built from linked togetherAudioNodes. In contrast with a standardAudioContext, anOfflineAudioContextdoesn't really render the audio but rather generates it, as fast as it can, in a buffer. complete(event)- The
completeevent is fired when the rendering of anOfflineAudioContextis terminated. OfflineAudioCompletionEvent- The
OfflineAudioCompletionEventrepresents events that occur when the processing of anOfflineAudioContextis terminated. Thecompleteevent implements this interface.
Interfaces obsoletas
As interfaces a seguir foram definidas em versões antigas das especificações da API de Web Audio, mas agora elas estão obsoletas e serão substituidas por outras interfaces.
JavaScriptNode- Used for direct audio processing via JavaScript. This interface is obsolete, and has been replaced by
ScriptProcessorNode. WaveTableNode- Used to define a periodic waveform. This interface is obsolete, and has been replaced by
PeriodicWave.
Exemplo
Este exemplo mostra uma grande variedade de funções da API de Web Audio que podem ser utilizadas. Você pode ver este código em ação na demo Voice-change-o-matic (também verificar o código-fonte completo no Github) - esta é uma demonstração de um modificador de voz de brinquedo experimental; aconselhamos manter seus alto-falantes baixo ao utilizá-lo, pelo menos para começar!
As linhas API de Web Audio estão destacadas; se você quiser encontrar mais informações sobre os diferentes métodos, faça uma busca através das páginas de referência.
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // define audio context
// Webkit/blink browsers need prefix, Safari won't work without window.
var voiceSelect = document.getElementById("voice"); // select box for selecting voice effect options
var visualSelect = document.getElementById("visual"); // select box for selecting audio visualization options
var mute = document.querySelector('.mute'); // mute button
var drawVisual; // requestAnimationFrame
var analyser = audioCtx.createAnalyser();
var distortion = audioCtx.createWaveShaper();
var gainNode = audioCtx.createGain();
var biquadFilter = audioCtx.createBiquadFilter();
function makeDistortionCurve(amount) { // function to make curve shape for distortion/wave shaper node to use
var k = typeof amount === 'number' ? amount : 50,
n_samples = 44100,
curve = new Float32Array(n_samples),
deg = Math.PI / 180,
i = 0,
x;
for ( ; i < n_samples; ++i ) {
x = i * 2 / n_samples - 1;
curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
}
return curve;
};
navigator.getUserMedia (
// constraints - only audio needed for this app
{
audio: true
},
// Success callback
function(stream) {
source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(gainNode);
gainNode.connect(audioCtx.destination); // connecting the different audio graph nodes together
visualize(stream);
voiceChange();
},
// Error callback
function(err) {
console.log('The following gUM error occured: ' + err);
}
);
function visualize(stream) {
WIDTH = canvas.width;
HEIGHT = canvas.height;
var visualSetting = visualSelect.value;
console.log(visualSetting);
if(visualSetting == "sinewave") {
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount; // half the FFT value
var dataArray = new Uint8Array(bufferLength); // create an array to store the data
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray); // get waveform data and put it into the array created above
canvasCtx.fillStyle = 'rgb(200, 200, 200)'; // draw wave with canvas
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / bufferLength;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = v * HEIGHT/2;
if(i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height/2);
canvasCtx.stroke();
};
draw();
} else if(visualSetting == "off") {
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
canvasCtx.fillStyle = "red";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
}
}
function voiceChange() {
distortion.curve = new Float32Array;
biquadFilter.gain.value = 0; // reset the effects each time the voiceChange function is run
var voiceSetting = voiceSelect.value;
console.log(voiceSetting);
if(voiceSetting == "distortion") {
distortion.curve = makeDistortionCurve(400); // apply distortion to sound using waveshaper node
} else if(voiceSetting == "biquad") {
biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = 25; // apply lowshelf filter to sounds using biquad
} else if(voiceSetting == "off") {
console.log("Voice settings turned off"); // do nothing, as off option was chosen
}
}
// event listeners to change visualize and voice settings
visualSelect.onchange = function() {
window.cancelAnimationFrame(drawVisual);
visualize(stream);
}
voiceSelect.onchange = function() {
voiceChange();
}
mute.onclick = voiceMute;
function voiceMute() { // toggle to mute and unmute sound
if(mute.id == "") {
gainNode.gain.value = 0; // gain set to 0 to mute sound
mute.id = "activated";
mute.innerHTML = "Unmute";
} else {
gainNode.gain.value = 1; // gain set to 1 to unmute sound
mute.id = "";
mute.innerHTML = "Mute";
}
}
Especificações
| Especificação | Status | Comentário |
|---|---|---|
| Web Audio API | Working Draft |
Compatibilidade de navegadores
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 14 webkit | 23 | Não suportado | 15 webkit 22 (unprefixed) |
6 webkit |
| Feature | Android | Chrome | Firefox Mobile (Gecko) | Firefox OS | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic support | Não suportado | 28 webkit | 25 | 1.2 | Não suportado | Não suportado | 6 webkit |
Veja também
- Using the Web Audio API
- Visualizations with Web Audio API
- Voice-change-O-matic example
- Violent Theremin example
- Web audio spatialisation basics
- Mixing Positional Audio and WebGL
- Developing Game Audio with the Web Audio API
- Porting webkitAudioContext code to standards based AudioContext
- Tones: a simple library for playing specific tones/notes using the Web Audio API.