aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/web_audio_api/index.html
blob: 9bfa53d259e96563b0c007ee0a9c3e9a97e122b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
---
title: Web Audio API
slug: Web/API/Web_Audio_API
tags:
  - API
  - Guide
  - NeedsTranslation
  - Reference
  - Référence(2)
  - TopicStub
  - Web Audio API
translation_of: Web/API/Web_Audio_API
---
<div>
<p>Web audio API - мощный и многогранный инструмент для манипуляции звуковой составляющей на веб-странице, что даёт возможность разработчикам выбрать источники, добавить к ним специальные звуковые эффекты (такие как panning), визуализировать их и многое другое.</p>
</div>

<h2 id="Общие_концепции_и_использование_Web_Audio">Общие концепции и использование Web Audio</h2>

<p>Web audio API позволяет обрабатывать операции над аудио с помощью специального аудио контекста (audio context), и был спроектирован на использование модульной маршрутизации (modular routing). Базовые операции выполняются с помощью аудио узлов (audio nodes), которые объединяются вместе, формируя аудио-маршрутизатору *таблицу (audio routing graph). Несколько источников - с разными видами поточных схем - поддерживаются даже изнутри простого контекста. Эта модульная концепция обеспечивает гибкость в создании сложных функций для динамических эффектов.</p>

<p>Аудио узлы объединяются в цепи и простые сети их вводами и выводами. Они, как правило, запускаются с одним или более источниками. Источники представляют собой массивы сэмплов на единицу времени. Например, при частоте дискретизации 44100 Гц, в каждой секунде каждого канала расположено 22050 сэмплов. Они могут быть либо  обработаны математически (смотрите : OscillatorNode), либо считаны с звуко/видео файлов (смотрите : AudioBufferSourceNode и  MediaElementAudioSourceNode) или с аудио потоков (смотрите : MediaStreamAudioSourceNode). По факту, звуковые файлы - просто запись звуковых колебаний, которые поступают от микрофона и музыкальных инструментов, смешиваясь в одну сложную волну. Выводные данные этих узлов могут быть связаны с вводными других, что смешивают или модифицируют потоки звуковых образцов в иные потоки. Популярная модификация - умножение образца на значение, чтобы сделать выходной звук менее или более громким (смотрите : GainMode). Когда звук был успешно обработан предназначенным ему эффектом, он может быть привязан к выходному потоку (смотрите : AudioContext.destination), что направляет звук в динамики или микрофон. Данный шаг нужен лишь если вы предпочтёте дать возможность пользователю услышать ваши шедевры.</p>

<p>Простой, типичный порядок действий выполнения манипуляций над аудио выглядит так :</p>

<ol>
 <li>Создадим аудио контекст</li>
 <li>Внутри нашего контекста определим источники - такие как &lt;audio&gt;, генератор (oscillator), поток</li>
 <li>Определим узлы эффектов, такие как реверберация (reverb), биквадратный фильтр (biquad filter), панорамирование (panner), сжатие (compressor)</li>
 <li>Выберем конечную точку аудио сигнала, например ваши системные звуковые устройства</li>
 <li>Привяжем наши источники к эффектам, и эффекты к конечному сигналу.</li>
</ol>

<p><img alt="A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information." src="https://mdn.mozillademos.org/files/7893/web-audio-api-flowchart.png" style="display: block; height: 113px; margin: 0px auto; width: 635px;"></p>

<p>Распределение времени контролируется с высокой точностью и низкими задержками, позволяя разработчикам писать код, что точно реагирует на события и в состоянии обработать образец даже на высокой оценке образцов (sample rate). Так что такие приложения как ритм-компьютер и программный автомат всегда под рукой.</p>

<p>Web audio API также даёт нам возможность контролировать то, каким аудио является в пространстве. Используя особую систему, что базируется<br>
 на модели source-listener, он позволяет контролировать модель панорамирования и обходиться без дистанционно-вызванного ослабления (distance-induced attenuation) или duppler shift, вызванного сдвигом источника (или сдвигом слушателя).</p>

<div class="note">
<p>Помните: вы можете прочитать более детальный теоретический материал о Web audio API в нашей статье<a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API"> Basic concepts behind Web Audio API</a>.</p>
</div>

<h2 id="Web_Audio_API_интерфейсы">Web Audio API интерфейсы</h2>

<p>В Web audio API есть всего 28 интерфейсов и соответствующих событий, которые мы сгруппировали в 9 категорий по функциональности.</p>

<h3 id="Главные_объекты_определения_аудио">Главные объекты определения аудио</h3>

<p>Главные контейнеры и определения, что формируют аудио объект в Web Audio API.</p>

<dl>
 <dt>{{domxref("AudioContext")}}</dt>
 <dd>AudioContext представляет собой некий аудио обрабатывающий объект, сооружённый из аудио модулей связанных вместе, где каждый является экземпляром класса {{domxref("AudioNode")}}. AudioContext управляет созданием узлов, содержащихся в нём и выполняет обработку или декодирование аудио данных.</dd>
 <dt>{{domxref("AudioNode")}}</dt>
 <dd>Интерфейс AudioNode представляет собой некий обрабатывающий  модуль такой как источник аудио  (то есть HTML &lt;audio&gt; или &lt;video&gt; элемент), конечный аудио объект, модуль непосредственной обработки (например фильтр BiquadFilterNode или звуковой контроллер такой как GainNode).</dd>
 <dt>{{domxref("AudioParam")}}</dt>
 <dd><code>Интерфейс </code><strong><code>AudioParam </code></strong><code>представляет аудио-параметры связанные с </code>{{domxref("AudioNode")}}. Он может содержать как точное значение параметра, так и параметры изменяющиеся во времени.</dd>
 <dt>{{event("ended_(Web_Audio)", "ended")}} (event)</dt>
 <dd>Событие <strong>ended </strong>генерируется тогда, когда воспроизведение остановлено по причине окончания носителя.</dd>
 <dt></dt>
</dl>

<h3 id="Источники_звука">Источники звука</h3>

<p>Интерфейсы, которые определяют источники звука для использования в Web Audio API.</p>

<dl>
 <dt>{{domxref("OscillatorNode")}}</dt>
 <dd><strong><code style="font-size: 14px;">OscillatorNode</code></strong><strong> </strong>представляет собой источник синусоидальной волны. Это модуль {{domxref("AudioNode")}} который принимает на вход <em>частоту </em>и генерирует синусоидальную волну с этой частотой.</dd>
 <dt>{{domxref("AudioBuffer")}}</dt>
 <dd>Интерфейс <strong><code>AudioBuffer</code></strong> представляет собой короткий аудио сэмпл находящийся в памяти, созданный из аудио файла с использованием метода {{ domxref("AudioContext.decodeAudioData()") }}, или созданный из необработанных(сырых) данных с использованием метода {{ domxref("AudioContext.createBuffer()") }}. После декодирования аудио данные могут быть помещены в {{ domxref("AudioBufferSourceNode") }}.</dd>
 <dt>{{domxref("AudioBufferSourceNode")}}</dt>
 <dd><code>Интерфейс </code><strong><code>AudioBufferSourceNode </code></strong><code>представляет собой источник звука, состоящий из аудио данных, хранящихся в </code>{{domxref("AudioBuffer")}}. Это {{domxref("AudioNode")}}, который действует в качестве источника звука.</dd>
 <dt>{{domxref("MediaElementAudioSourceNode")}}</dt>
 <dd>Интерфейс <code><strong>MediaElementAudio</strong></code><strong><code>SourceNode</code></strong> представляет источник звука, содержащегося в элементе HTML5 {{ htmlelement("audio") }} или {{ htmlelement("video") }} .  Это {{domxref("AudioNode")}}, который действует в качестве источника звука.</dd>
 <dt>{{domxref("MediaStreamAudioSourceNode")}}</dt>
 <dd>Интерфейс <code><strong>MediaStreamAudio</strong></code><strong><code>SourceNode</code></strong> представляет источник звука, содержащегося в потоке  <a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> {{domxref("MediaStream")}} (например веб-камеры или микрофона). Это {{domxref("AudioNode")}}, который действует в качестве источника звука.</dd>
</dl>

<h3 id="Аудио_фильтры">Аудио фильтры</h3>

<p>Интерфейсы для определения эффектов которые можно применить к источникам звука.</p>

<dl>
 <dt>{{domxref("BiquadFilterNode")}}</dt>
 <dd><strong><code>BiquadFilterNode </code></strong><code>представляет простой фильтр низкого порядка. Это </code>{{domxref("AudioNode")}} представляющий различные виды фильтров такие как эквалайзер или управление тональностью. <strong><code>BiquadFilterNode</code></strong><code> имеет ровно один вход и один выход.</code></dd>
 <dt>{{domxref("ConvolverNode")}}</dt>
 <dd><code><strong>Convolver</strong></code><strong><code>Node</code></strong><strong> </strong>это <span style="line-height: 1.5;">{{domxref("AudioNode")}} выполняющий линейную свёртку </span><span style="line-height: 1.5;">AudioBuffer, часто применяется для достижения эффекта реверберации по заданной импульсной характеристике.</span></dd>
 <dt>{{domxref("DelayNode")}}</dt>
 <dd><strong><code>DelayNode</code></strong><strong> </strong>представляет собой линию задержки (<a href="http://en.wikipedia.org/wiki/Digital_delay_line">delay-line</a>); содержит {{domxref("AudioNode")}} вызывающий задержку между выходным и входным сигналом.</dd>
 <dt>{{domxref("DynamicsCompressorNode")}}</dt>
 <dd>The <strong><code>DynamicsCompressorNode</code></strong> 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.</dd>
 <dt>{{domxref("GainNode")}}</dt>
 <dd>The <strong><code>GainNode</code></strong><strong> </strong>interface represents a change in volume. It is an {{domxref("AudioNode")}} audio-processing module that causes a given <em>gain</em> to be applied to the input data before its propagation to the output.</dd>
 <dt>{{domxref("StereoPannerNode")}}</dt>
 <dd>The <code><strong>StereoPannerNode</strong></code> interface represents a simple stereo panner node  that can be used to pan an audio stream left or right.</dd>
 <dt>{{domxref("WaveShaperNode")}}</dt>
 <dd>The <strong><code>WaveShaperNode</code></strong><strong> </strong>interface represents a non-linear distorter. It is an {{domxref("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.</dd>
 <dt>{{domxref("PeriodicWave")}}</dt>
 <dd>Used to define a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.</dd>
</dl>

<h3 id="Defining_audio_destinations">Defining audio destinations</h3>

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

<dl>
 <dt>{{domxref("AudioDestinationNode")}}</dt>
 <dd>The <strong><code>AudioDestinationNode</code></strong> interface represents the end destination of an audio source in a given context — usually the speakers of your device.</dd>
 <dt>{{domxref("MediaStreamAudioDestinationNode")}}</dt>
 <dd>The <code><strong>MediaStreamAudio</strong></code><strong><code>DestinationNode</code></strong> interface represents an audio destination consisting of a <a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> {{domxref("MediaStream")}} with a single <code>AudioMediaStreamTrack</code>, which can be used in a similar way to a MediaStream obtained from {{ domxref("Navigator.getUserMedia") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.</dd>
</dl>

<h3 id="Анализ_и_визуализация_данных">Анализ и визуализация данных</h3>

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

<dl>
 <dt>{{domxref("AnalyserNode")}}</dt>
 <dd>The <strong><code>AnalyserNode</code></strong> interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.</dd>
</dl>

<h3 id="Splitting_and_merging_audio_channels">Splitting and merging audio channels</h3>

<p>To split and merge audio channels, you'll use these interfaces.</p>

<dl>
 <dt>{{domxref("ChannelSplitterNode")}}</dt>
 <dd>The <code><strong>ChannelSplitterNode</strong></code> interface separates the different channels of an audio source out into a set of <em>mono</em> outputs.</dd>
 <dt>{{domxref("ChannelMergerNode")}}</dt>
 <dd>The <code><strong>ChannelMergerNode</strong></code> interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.</dd>
</dl>

<h3 id="Audio_spatialization">Audio spatialization</h3>

<p>These interfaces allow you to add audio spatialization panning effects to your audio sources.</p>

<dl>
 <dt>{{domxref("AudioListener")}}</dt>
 <dd>The <strong><code>AudioListener</code></strong><strong> </strong>interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.</dd>
 <dt>{{domxref("PannerNode")}}</dt>
 <dd>The <strong><code>PannerNode</code></strong><strong> </strong>interface represents the behavior of a signal in space. It is an {{domxref("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.</dd>
</dl>

<h3 id="Audio_processing_via_JavaScript">Audio processing via JavaScript</h3>

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

<div class="note">
<p><strong>Note</strong>: 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 {{ anch("Audio_Workers") }}.</p>
</div>

<dl>
 <dt>{{domxref("ScriptProcessorNode")}}</dt>
 <dd>The <strong><code>ScriptProcessorNode</code></strong><strong> </strong>interface allows the generation, processing, or analyzing of audio using JavaScript. It is an {{domxref("AudioNode")}} audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the {{domxref("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.</dd>
 <dt>{{event("audioprocess")}} (event)</dt>
 <dd>The <code>audioprocess</code> event is fired when an input buffer of a Web Audio API {{domxref("ScriptProcessorNode")}} is ready to be processed.</dd>
 <dt>{{domxref("AudioProcessingEvent")}}</dt>
 <dd>The <a href="/en-US/docs/Web_Audio_API" title="/en-US/docs/Web_Audio_API">Web Audio API</a> <code>AudioProcessingEvent</code> represents events that occur when a {{domxref("ScriptProcessorNode")}} input buffer is ready to be processed.</dd>
</dl>

<h3 id="Offlinebackground_audio_processing">Offline/background audio processing</h3>

<p>It is possible to process/render an audio graph very quickly in the background — rendering it to an {{domxref("AudioBuffer")}} rather than to the device's speakers — with the following.</p>

<dl>
 <dt>{{domxref("OfflineAudioContext")}}</dt>
 <dd>The <strong><code>OfflineAudioContext</code></strong> interface is an {{domxref("AudioContext")}} interface representing an audio-processing graph built from linked together {{domxref("AudioNode")}}s. In contrast with a standard <code>AudioContext</code>, an <code>OfflineAudioContext</code> doesn't really render the audio but rather generates it, <em>as fast as it can</em>, in a buffer.</dd>
 <dt>{{event("complete")}} (event)</dt>
 <dd>The <code>complete</code> event is fired when the rendering of an {{domxref("OfflineAudioContext")}} is terminated.</dd>
 <dt>{{domxref("OfflineAudioCompletionEvent")}}</dt>
 <dd>The <code>OfflineAudioCompletionEvent</code> represents events that occur when the processing of an {{domxref("OfflineAudioContext")}} is terminated. The {{event("complete")}} event implements this interface.</dd>
</dl>

<h3 id="Audio_Workers" name="Audio_Workers">Audio Workers</h3>

<p>Audio workers provide the ability for direct scripted audio processing to be done inside a <a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">web worker</a> 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 {{domxref("ScriptProcessorNode")}}, and the other features discussed in the <a href="#Audio_processing_via_JavaScript">Audio processing via JavaScript</a> section above.</p>

<dl>
 <dt>{{domxref("AudioWorkerNode")}}</dt>
 <dd>The AudioWorkerNode interface represents an {{domxref("AudioNode")}} that interacts with a worker thread to generate, process, or analyse audio directly.</dd>
 <dt>{{domxref("AudioWorkerGlobalScope")}}</dt>
 <dd>The <code>AudioWorkerGlobalScope</code> interface is a <code>DedicatedWorkerGlobalScope</code>-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.</dd>
 <dt>{{domxref("AudioProcessEvent")}}</dt>
 <dd>This is an <code>Event</code> object that is dispatched to {{domxref("AudioWorkerGlobalScope")}} objects to perform processing.</dd>
</dl>

<h2 id="Example" name="Example">Obsolete interfaces</h2>

<p>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.</p>

<dl>
 <dt>{{domxref("JavaScriptNode")}}</dt>
 <dd>Used for direct audio processing via JavaScript. This interface is obsolete, and has been replaced by {{domxref("ScriptProcessorNode")}}.</dd>
 <dt>{{domxref("WaveTableNode")}}</dt>
 <dd>Used to define a periodic waveform. This interface is obsolete, and has been replaced by {{domxref("PeriodicWave")}}.</dd>
</dl>

<h2 id="Example" name="Example">Пример</h2>

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

<p>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.</p>

<pre class="brush: js; highlight:[1,2,9,10,11,12,36,37,38,39,40,41,62,63,72,114,115,121,123,124,125,147,151] notranslate">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 &lt; 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 &lt; 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";
  }
}
</pre>

<h2 id="Определения">Определения</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('Web Audio API')}}</td>
   <td>{{Spec2('Web Audio API')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Поддержка_браузерами">Поддержка браузерами</h2>

<p>{{Compat("api.AudioContext", 0)}}</p>

<h2 id="Смотрите_также">Смотрите также</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li>
 <li><a href="/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API">Visualizations with Web Audio API</a></li>
 <li><a href="http://mdn.github.io/voice-change-o-matic/">Voice-change-O-matic example</a></li>
 <li><a href="http://mdn.github.io/violent-theremin/">Violent Theremin example</a></li>
 <li><a href="/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialisation_basics">Web audio spatialisation basics</a></li>
 <li><a href="http://www.html5rocks.com/tutorials/webaudio/positional_audio/">Mixing Positional Audio and WebGL</a></li>
 <li><a href="http://www.html5rocks.com/tutorials/webaudio/games/">Developing Game Audio with the Web Audio API</a></li>
 <li><a href="/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext" title="/en-US/docs/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext">Porting webkitAudioContext code to standards based AudioContext</a></li>
 <li><a href="https://github.com/bit101/tones">Tones</a>: a simple library for playing specific tones/notes using the Web Audio API.</li>
 <li><a href="https://github.com/goldfire/howler.js/">howler.js</a>: a JS audio library that defaults to <a href="https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html">Web Audio API</a> and falls back to <a href="http://www.whatwg.org/specs/web-apps/current-work/#the-audio-element">HTML5 Audio</a>, as well as providing other useful features.</li>
 <li><a href="https://github.com/mattlima/mooog">Mooog</a>: jQuery-style chaining of AudioNodes, mixer-style sends/returns, and more.</li>
</ul>

<section id="Quick_Links">
<h3 id="Quicklinks">Quicklinks</h3>

<ol>
 <li data-default-state="open"><strong><a href="#">Guides</a></strong>

  <ol>
   <li><a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API">Basic concepts behind Web Audio API</a></li>
   <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li>
   <li><a href="/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API">Visualizations with Web Audio API</a></li>
   <li><a href="/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialisation_basics">Web audio spatialisation basics</a></li>
   <li><a href="/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext" title="/en-US/docs/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext">Porting webkitAudioContext code to standards based AudioContext</a></li>
  </ol>
 </li>
 <li data-default-state="open"><strong><a href="#">Examples</a></strong>
  <ol>
   <li><a href="http://mdn.github.io/voice-change-o-matic/">Voice-change-O-matic</a></li>
   <li><a href="http://mdn.github.io/violent-theremin/">Violent Theremin</a></li>
  </ol>
 </li>
 <li data-default-state="open"><strong><a href="#">Interfaces</a></strong>
  <ol>
   <li>{{domxref("AnalyserNode")}}</li>
   <li>{{domxref("AudioBuffer")}}</li>
   <li>{{domxref("AudioBufferSourceNode")}}</li>
   <li>{{domxref("AudioContext")}}</li>
   <li>{{domxref("AudioDestinationNode")}}</li>
   <li>{{domxref("AudioListener")}}</li>
   <li>{{domxref("AudioNode")}}</li>
   <li>{{domxref("AudioParam")}}</li>
   <li>{{event("audioprocess")}} (event)</li>
   <li>{{domxref("AudioProcessingEvent")}}</li>
   <li>{{domxref("BiquadFilterNode")}}</li>
   <li>{{domxref("ChannelMergerNode")}}</li>
   <li>{{domxref("ChannelSplitterNode")}}</li>
   <li>{{event("complete")}} (event)</li>
   <li>{{domxref("ConvolverNode")}}</li>
   <li>{{domxref("DelayNode")}}</li>
   <li>{{domxref("DynamicsCompressorNode")}}</li>
   <li>{{event("ended_(Web_Audio)", "ended")}} (event)</li>
   <li>{{domxref("GainNode")}}</li>
   <li>{{domxref("MediaElementAudioSourceNode")}}</li>
   <li>{{domxref("MediaStreamAudioDestinationNode")}}</li>
   <li>{{domxref("MediaStreamAudioSourceNode")}}</li>
   <li>{{domxref("OfflineAudioCompletionEvent")}}</li>
   <li>{{domxref("OfflineAudioContext")}}</li>
   <li>{{domxref("OscillatorNode")}}</li>
   <li>{{domxref("PannerNode")}}</li>
   <li>{{domxref("PeriodicWaveNode")}}</li>
   <li>{{domxref("ScriptProcessorNode")}}</li>
   <li>{{domxref("WaveShaperNode")}}</li>
  </ol>
 </li>
</ol>
</section>