Статьи

Web Audio API

  1. Загальні концепції та використання Web Audio
  2. Web Audio API інтерфейси
  3. Головні об'єкти визначення аудіо
  4. джерела звуку
  5. Аудіо фільтри
  6. Defining audio destinations
  7. Аналіз і візуалізація даних
  8. Splitting and merging audio channels
  9. Audio spatialization
  10. Audio processing via JavaScript
  11. Offline / background audio processing
  12. Audio Workers
  13. Obsolete interfaces
  14. приклад
  15. визначення
  16. підтримка браузерами

Web audio API - потужний і багатогранний інструмент для маніпуляції звукової складової на веб-сторінці, що дає можливість розробникам вибрати джерела, додати до них спеціальні звукові ефекти (такі як panning), візуалізувати їх і багато іншого.

Загальні концепції та використання Web Audio

Web audio API дозволяє обробляти операції над аудіо за допомогою спеціального аудіо контексту (audio context), і був спроектований на використання модульної маршрутизації (modular routing). Базові операції виконуються за допомогою аудіо вузлів (audio nodes), що об'єднуються разом, формуючи аудіо-маршрутізаторную * таблицю (audio routing graph). Кілька джерел - з різними видами поточних схем - підтримуються навіть зсередини простого контексту. Ця модульна концепція забезпечує гнучкість в створенні складних функцій для динамічних ефектів.

Аудіо вузли об'єднуються в ланцюзі і прості мережі їх уведеннями та висновками. Вони, як правило, запускаються з одним або більше джерелами. Джерела являють собою масиви семплів на одиницю часу. Наприклад, при частоті дискретизації 44100 Гц, в кожній секунді кожного каналу розташовано 22050 семплів. Вони можуть бути або оброблені математично (дивіться: OscillatorNode), або лічені з звуко / відео файлів (дивіться: AudioBufferSourceNode і MediaElementAudioSourceNode) або з аудіо потоків (дивіться: MediaStreamAudioSourceNode). За фактом, звукові файли - просто запис звукових коливань, які надходять від мікрофона і музичних інструментів, змішуючись в одну складну хвилю. Вивідні дані цих вузлів можуть бути пов'язані з вступними інших, що змішують або модифікують потоки звукових зразків у Зовсім інші потоки. Популярна модифікація - множення зразка на значення, щоб зробити вихідний звук менш або більш гучним (дивіться: GainMode). Коли звук був успішно оброблений призначеним йому ефектом, він може бути прив'язаний до вихідного потоку (дивіться: AudioContext.destination), що направляє звук в динаміки або мікрофон. Даний крок потрібен лише якщо ви віддасте перевагу дати можливість користувачеві почути ваші шедеври.

Простий, типовий порядок дій виконання маніпуляцій над аудіо виглядає так:

  1. Створимо аудіо контекст
  2. Всередині нашого контексту визначимо джерела - такі як <audio>, генератор (oscillator), потік
  3. Визначимо вузли ефектів, такі як реверберація (reverb), біквадратних фільтр (biquad filter), панораммірованіе (panner), стиснення (compressor)
  4. Виберемо кінцеву точку аудіо сигналу, наприклад ваші системні звукові пристрої
  5. Прив'яжемо наші джерела до ефектів, і ефекти до кінцевого сигналу.

Створимо аудіо контекст   Всередині нашого контексту визначимо джерела - такі як <audio>, генератор (oscillator), потік   Визначимо вузли ефектів, такі як реверберація (reverb), біквадратних фільтр (biquad filter), панораммірованіе (panner), стиснення (compressor)   Виберемо кінцеву точку аудіо сигналу, наприклад ваші системні звукові пристрої   Прив'яжемо наші джерела до ефектів, і ефекти до кінцевого сигналу

Розподіл часу контролюється з високою точністю і низькими затримками, дозволяючи розробникам писати код, що точно реагує на події і в змозі обробити зразок навіть на високій оцінці зразків (sample rate). Так що такі додатки як ритм-комп'ютер і програмний автомат завжди під рукою.

Web audio API також дає нам можливість контролювати те, яким аудіо є в просторі. Використовуючи особливу систему, що базується
на моделі source-listener, він дозволяє контролювати модель панораммірованія і обходитися без дистанційно-викликаних ослаблення (distance-induced attenuation) або duppler shift, викликаного зсувом джерела (або зрушенням слухача).

Пам'ятайте: Ви можете прочитати більш детальний теоритический матеріал про Web audio API в нашій статті Basic concepts behind Web Audio API .

Web Audio API інтерфейси

У Web audio API є всього 28 інтерфейсів і відповідних подій, які ми cгруппіровалі в 9 категорій по функціональності.

Головні об'єкти визначення аудіо

Головні контейнери і визначення, що формують аудіо об'єкт в Web Audio API.

AudioContext

AudioContext являє собою якийсь аудіо обробляє об'єкт, споруджений з аудіо модулів пов'язаних разом, де кожен є екземпляром класу AudioNode . AudioContext управляє створенням вузлів, що містяться в ньому і виконує обробку або декодування аудіо даних. AudioNode Інтерфейс AudioNode являє собою якийсь обробляє модуль такий як джерело аудіо (тобто HTML <audio> або <video> елемент), кінцевий аудіо об'єкт, модуль безпосередньої обробки (наприклад фільтр BiquadFilterNode або звуковий контролер такий як GainNode). AudioParam Інтерфейс AudioParam представляє аудіо-параметри пов'язані з AudioNode . Він може містити як точне значення параметра, так і параметри змінюються в часі. ended (event) Подія ended генерується тоді, коли відтворення зупинено через закінчення носія.

джерела звуку

Інтерфейси, які визначають джерела звуку для використання в Web Audio API.

OscillatorNode OscillatorNode

являє собою джерело синусоїдальної хвилі. це модуль AudioNode який приймає на вхід частоту і генерує синусоїдальну хвилю з цією частотою. AudioBuffer Інтерфейс AudioBuffer є короткий аудіо семпл знаходиться в пам'яті, створений з аудіо файлу з використанням методу AudioContext.decodeAudioData () , Або створений з необроблених (сирих) даних з використанням методу AudioContext.createBuffer () . Після декодування аудіо дані можуть бути поміщені в AudioBufferSourceNode . AudioBufferSourceNode Інтерфейс AudioBufferSourceNode є джерело звуку, що складається з аудіо даних, що зберігаються в AudioBuffer . це AudioNode , Який діє в якості джерела звуку. MediaElementAudioSourceNode Інтерфейс MediaElementAudio SourceNode представляє джерело звуку, що міститься в елементі HTML5 <Audio> або <Video> . це AudioNode , Який діє в якості джерела звуку. MediaStreamAudioSourceNode Інтерфейс MediaStreamAudio SourceNode представляє джерело звуку, що міститься в потоці WebRTC MediaStream (Наприклад веб-камери або мікрофона). це AudioNode , Який діє в якості джерела звуку.

Аудіо фільтри

Інтерфейси для визначення ефектів які можна застосувати до джерел звуку.

BiquadFilterNode BiquadFilterNode

представляє простий фільтр низького порядку. це AudioNode представляє різні види фільтрів такі як еквалайзер або управління тональністю. BiquadFilterNode має рівно один вхід і один вихід. ConvolverNode Convolver Node це AudioNode виконує лінійну згортку AudioBuffer, часто застосовується для досягнення ефекту реверберації по заданій імпульсної характеристиці. DelayNode DelayNode являє собою лінію затримки ( delay-line ); містить AudioNode викликає затримку між вихідним і вхідним сигналом. DynamicsCompressorNode The DynamicsCompressorNode interface 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 GainNode interface represents a change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output . StereoPannerNode The StereoPannerNode interface represents a simple stereo panner node that can be used to pan an audio stream left or right . WaveShaperNode The WaveShaperNode interface represents a non-linear distorter. It is an AudioNode that 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 .

Defining audio destinations

Once you are done processing your audio, these interfaces define where to output it.

AudioDestinationNode The AudioDestinationNode interface represents the end destination of

an audio source in a given context - usually the speakers of your device. MediaStreamAudioDestinationNode The MediaStreamAudio DestinationNode interface represents an audio destination consisting of a WebRTC MediaStream with a single AudioMediaStreamTrack, which can be used in a similar way to a MediaStream obtained from Navigator.getUserMedia . It is an AudioNode that acts as an audio destination.

Аналіз і візуалізація даних

If you want to extract time, frequency and other data from your audio, the AnalyserNode is what you need.

AnalyserNode The AnalyserNode interface represents a node able to

provide real -time frequency and time-domain analysis information, for the purposes of data analysis and visualization.

Splitting and merging audio channels

To split and merge audio channels, you'll use these interfaces.

ChannelSplitterNode The ChannelSplitterNode interface separates the different channels of

an audio source out into a set of mono outputs . ChannelMergerNode The ChannelMergerNode interface reunites different mono inputs into a single output . 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 AudioListener interface represents the position and orientation

of the unique person listening to the audio scene used in audio spatialization . PannerNode The PannerNode interface represents the behavior of a signal in space . It is an AudioNode audio-processing module describing its position with right-hand Cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.

Audio processing via JavaScript

If you want to use an external script to process your audio source, the below Node and events make it possible.

Note: As of the August 29 2014 Web Audio API spec publication, these features have been marked as deprecated, and are soon to be replaced by Audio_Workers .

ScriptProcessorNode

The ScriptProcessorNode interface allows the generation, processing, or analyzing of audio using JavaScript. It is an AudioNode audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the AudioProcessingEvent interface, 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 audioprocess event is fired when an input buffer of a Web Audio API ScriptProcessorNode is ready to be processed. AudioProcessingEvent The Web Audio API AudioProcessingEvent represents events that occur when a ScriptProcessorNode input buffer is ready to be processed.

Offline / background audio processing

It is possible to process / render an audio graph very quickly in the background - rendering it to an AudioBuffer rather than to the device's speakers - with the following.

OfflineAudioContext

The OfflineAudioContext interface is an AudioContext interface representing an audio-processing graph built from linked together AudioNode s. In contrast with a standard AudioContext, an OfflineAudioContext does not really render the audio but rather generates it , as fast as it can, in a buffer. complete (Event) The complete event is fired when the rendering of an OfflineAudioContext is terminated. OfflineAudioCompletionEvent The OfflineAudioCompletionEvent represents events that occur when the processing of an OfflineAudioContext is terminated. The complete event implements this interface.

Audio Workers

Audio workers provide the ability for direct scripted audio processing to be done inside a web worker context, and are defined by a couple of interfaces (new as of 29th August 2014.) These are not implemented in any browsers yet. When implemented, they will replace ScriptProcessorNode , And the other features discussed in the Audio processing via JavaScript section above.

AudioWorkerNode

The AudioWorkerNode interface represents an AudioNode that interacts with a worker thread to generate, process, or analyse audio directly. AudioWorkerGlobalScope The AudioWorkerGlobalScope interface is a DedicatedWorkerGlobalScope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worker thread. AudioProcessEvent This is an Event object that is dispatched to AudioWorkerGlobalScope objects to perform processing.

Obsolete interfaces

The following interfaces were defined in old versions of the Web Audio API spec, but are now obsolete and have been replaced by other 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 .

приклад

This example shows a wide variety of Web Audio API functions being used. You can see this code in action on the Voice-change-o-matic demo (also check out the full source code at Github ) - this is an experimental voice changer toy demo; keep your speakers turned down low when you use it, at least to start!

The Web Audio API lines are highlighted; if you want to find more out about what the different methods, etc. do, have a search around the reference pages.

var audioCtx = new (window.AudioContext || window.webkitAudioContext) (); // define audio context // Webkit / blink browsers need prefix, Safari will not 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"; }}

визначення

Specification Status Comment Web Audio API Робочий чернетку

підтримка браузерами

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit) Базова підтримка 14 (Так) 23 Ні 15
22 (unprefixed) 6 Feature Android Chrome Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile Базова підтримка Ні 28 25 1.2 Ні Ні 6

Дивіться також

CreateBiquadFilter (); function makeDistortionCurve (amount) {// function to make curve shape for distortion / wave shaper node to use var k = typeof amount === 'number'?

Новости