forked from WebAudio/web-audio-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.bs
13440 lines (11070 loc) · 521 KB
/
index.bs
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class=metadata>
Title: Web Audio API
Shortname: webaudio
Level: 1
Group: audiowg
Status: ED
ED: https://webaudio.github.io/web-audio-api/
TR: https://www.w3.org/TR/webaudio/
Favicon: favicon.png
Previous Version: https://www.w3.org/TR/2021/CR-webaudio-20210114/
Previous Version: https://www.w3.org/TR/2020/CR-webaudio-20200611/
Previous Version: https://www.w3.org/TR/2018/CR-webaudio-20180918/
Previous Version: https://www.w3.org/TR/2018/WD-webaudio-20180619/
Previous Version: https://www.w3.org/TR/2015/WD-webaudio-20151208/
Previous Version: https://www.w3.org/TR/2013/WD-webaudio-20131010/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20121213/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20120802/
Previous Version: https://www.w3.org/TR/2012/WD-webaudio-20120315/
Previous Version: https://www.w3.org/TR/2011/WD-webaudio-20111215/
Editor: Paul Adenot, Mozilla (https://www.mozilla.org/), padenot@mozilla.com, w3cid 62410
Editor: Hongchan Choi, Google (https://www.google.com/), hongchan@google.com, w3cid 74103
Former Editor: Raymond Toy (until Oct 2018)
Former Editor: Chris Wilson (Until Jan 2016)
Former Editor: Chris Rogers (Until Aug 2013)
Implementation Report: implementation-report.html
Test Suite: https://github.com/web-platform-tests/wpt/tree/master/webaudio
Repository: WebAudio/web-audio-api
Abstract: This specification describes a high-level Web <abbr title="Application Programming Interface">API</abbr>
for processing and synthesizing audio in web applications.
The primary paradigm is of an audio routing graph,
where a number of {{AudioNode}} objects are connected together to define the overall audio rendering.
The actual processing will primarily take place in the underlying implementation
(typically optimized Assembly / C / C++ code),
but [[#AudioWorklet|direct script processing and synthesis]] is also supported.
The [[#introductory]] section covers the motivation behind this specification.
This API is designed to be used in conjunction with other APIs and elements on the web platform, notably:
XMLHttpRequest [[XHR]] (using the <code>responseType</code> and <code>response</code> attributes).
For games and interactive applications,
it is anticipated to be used with the <code>canvas</code> 2D [[2dcontext]]
and WebGL [[WEBGL]] 3D graphics APIs.
Markup Shorthands: markdown on, dfn on, css off
</pre>
<pre class=anchors>
spec: ECMAScript; url: https://tc39.github.io/ecma262/#sec-data-blocks; type: dfn; text: data block;
url: https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-getusermedia; type: method; for: MediaDevices; text: getUserMedia()
</pre>
<!-- We want {{object}} and {{Promise}} to go to the WebIDL object -->
<pre class=link-defaults>
spec:webidl; type:interface; text:object
spec:webidl; type:interface; text:Promise
</pre>
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML" as="script">
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/jax/output/HTML-CSS/jax.js?rev=2.7.5" as="script">
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/jax/output/HTML-CSS/fonts/STIX/fontdata.js?rev=2.7.5" as="script">
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js?rev=2.7.5" as="script">
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/jax/element/mml/optable/BasicLatin.js?rev=2.7.5" as="script">
<link rel="preload" href="https://www.w3.org/scripts/MathJax/2.7.5/jax/output/HTML-CSS/autoload/mtable.js?rev=2.7.5" as="script">
<script>
window.addEventListener("DOMContentLoaded", function () {
"use strict";
new Promise(function (resolve, reject) {
var mathjax = document.createElement('script');
var url = "https://www.w3.org/scripts/MathJax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
// Safari doesn't (yet) support load event on scripts so we have to poll. So 😢.
var id = setInterval(function () {
if (window.MathJax) {
clearInterval(id);
resolve();
}
}, 100);
mathjax.onload = function () {
clearInterval(id);
resolve();
};
mathjax.onerror = function (err) {
var error = (err instanceof Event) ? new Error(err.message) : err;
reject(error);
};
// Time out waiting after 20 seconds and reject.
setTimeout(function(){
mathjax.onerror(new Error("Loading timed out."));
}, 20000);
mathjax.id = "mathjax";
mathjax.src = url;
document.body.appendChild(mathjax);
}).then(function () {
MathJax.Hub.Config({
tex2jax: {
skipTags: ["script", "noscript", "style", "textarea", "code"]
}
});
}).catch(function (error) {
console.error(error);
});
});
</script>
<script>
// This replaces the contents of "divID" with an unordered list of all the
// amendment boxes with a prefix of "prefix". Each item of the list will be of
// the form "label n", where "label" is the specified label to use via "label".
// "n" is just a sequential number starting at 1.
//
// Example usage where we want a list of all the changes whose id begins with
// "c2361".
//
// (div id="change-list-2361")
// (/div)
//
// And add
//
// ListAmendments("c2361", "Correction", "change-list-2361")
//
// to the onload event listener at the bottom of this file.
//
// (Replace the "(", ")" with "<", ">", respectively above. Bikeshed mangles
// this if we use "<" above.
function ListAmendments(prefix, label, divID) {
// Find all the nodes whose id starts with prefix.
let nodes = document.querySelectorAll('*[id^="' + prefix + '"]');
// Find the div element which will be replaced by the unordered list.
let div = document.getElementById(divID);
// Create the unordered list
let text = '<ul>';
let index = 1;
nodes.forEach(x => {
text += '<li><a href="#' + x.id + '">' + label + ' ' + index + '</a></li>';
++index;
// Insert buttons for prev and next change
InsertButtons(x);
});
text += '</ul>';
div.innerHTML = text;
}
// Search for the class "amendment-buttons", and replace the contents of the div
// with a set of buttons which link to the previous and next related amendment.
function InsertButtons(node) {
let list = node.getElementsByClassName("amendment-buttons");
// We only add buttons to the first class inside the node.
if (list && list.length > 0) {
let matches = node.id.match(/([ac]\d+)-(\d+)/);
let changeID = matches[1];
let changeNum = parseInt(matches[2]);
// Create buttons.
let text = "";
if (changeNum > 1) {
// Add "previous" button, only if there is a previous change.
text += "<button onclick='location.href=";
text += '"#' + changeID + '-' + (changeNum-1) + '"';
text += "'>Previous Change</button>";
}
if (document.getElementById(changeID + "-" + (changeNum + 1))) {
// Add "next" button only if there is a next change
text += "<button onclick='location.href=";
text += '"#' + changeID + '-' + (changeNum + 1) + '"';
text += "'>Next Change</button>";
}
list[0].innerHTML = text;
}
}
window.addEventListener('load', (event) => {
// Add entries here for each change
ListAmendments("c2361", "Proposed Correction", "change-list-2361");
ListAmendments("c127", "Proposed Correction", "change-list-127");
ListAmendments("c2359", "Proposed Correction", "change-list-2359");
ListAmendments("c2373", "Proposed Correction", "change-list-2373");
ListAmendments("c2321", "Proposed Correction", "change-list-2321");
ListAmendments("c2375", "Proposed Correction", "change-list-2375");
ListAmendments("c2475", "Proposed Addition", "change-list-2475");
ListAmendments("c2444", "Proposed Addition", "change-list-2444");
});
</script>
<style>
@media (prefers-color-scheme: light) {
:root {
--div-info-fg-color: #178217;
}
}
@media (prefers-color-scheme: dark) {
:root {
--div-info-fg-color: springgreen;
}
}
.todo {
border: 1px solid red;
background-color: rgba(255, 0, 0, 0.3);
}
.todo:before {
content: "TODO:";
}
.synchronous:before {
content: "⌛ ";
}
.synchronous:hover{
border-bottom: 1px dotted gray;
}
body#respecDocument {
max-width: 60em;
}
.seclist > p {
font-style: italic;
}
table.channels {
width:100%;
overflow: auto;
margin: 0;
font-size: 14px;
font-family: /*Consolas, Monaco,*/ monospace;
}
table.channels th {
width:60px;
text-align:center;
}
table.channels td {
width:60px;
text-align:center;
}
@media (prefers-color-scheme: light) {
table.channels tr:nth-child(even) {
background: #EEE;
}
table.channels tr:nth-child(odd) {
background: #FFF;
}
}
@media (prefers-color-scheme: dark) {
table.channels tr:nth-child(even) {
background: var(--assertion-border)
}
}
div.node-info {
padding-left: 4em;
padding-right: 4em;
}
div.node-info > table {
border-collapse: collapse;
border-top: 2px solid #707070;
border-bottom: 2px solid #707070;
width: 100%;
margin: 2em 0;
}
div.node-info > table > tbody > tr > th,
div.node-info > table > tbody > tr > td {
padding: 0.2em 0.6em;
min-width: 150px;
border-top: 1px solid #ddd
}
div.node-info > table > thead > tr > th {
line-height: 2em;
font-weight: 600;
border-bottom: 1px solid #707070;
color: var(--div-info-fg-color);
}
div.audioparam-info {
padding-left: 4em;
padding-right: 4em;
}
div.audioparam-info > table {
border-collapse: collapse;
border-top: 2px solid #707070;
border-bottom: 2px solid #707070;
width: 100%;
margin: 2em 0;
}
div.audioparam-info > table > tbody > tr > th,
div.audioparam-info > table > tbody > tr > td {
padding: 0.2em 0.6em;
min-width: 150px;
border-top: 1px solid #ddd
}
div.audioparam-info > table > thead > tr > th {
line-height: 2em;
font-weight: 600;
border-bottom: 1px solid #707070;
color: var(--div-info-fg-color);
}
div.enum-description > table {
border-collapse: collapse;
border-top: 2px solid #707070;
border-bottom: 2px solid #707070;
width: 100%;
margin: 2em 0;
}
div.enum-description > table > tbody > tr > th,
div.enum-description > table > tbody > tr > td {
padding: 0.2em 0.6em;
min-width: 150px;
border-top: 1px solid #ddd
}
div.enum-description > table > thead > tr > th {
line-height: 2em;
font-weight: 600;
color: var(--div-info-fg-color);
border-bottom: 1px solid #707070;
}
code.nobreak {
white-space: nowrap;
}
</style>
<h2 id="introductory" class=no-num>
Introduction</h2>
Audio on the web has been fairly primitive up to this point and until
very recently has had to be delivered through plugins such as Flash and
QuickTime. The introduction of the <{audio}> element in HTML5
is very important, allowing for basic streaming audio playback. But, it
is not powerful enough to handle more complex audio applications. For
sophisticated web-based games or interactive applications, another
solution is required. It is a goal of this specification to include the
capabilities found in modern game audio engines as well as some of the
mixing, processing, and filtering tasks that are found in modern
desktop audio production applications.
The APIs have been designed with a wide variety of use cases
[[webaudio-usecases]] in mind. Ideally, it should be able to support
<i>any</i> use case which could reasonably be implemented with an
optimized C++ engine controlled via script and run in a browser. That
said, modern desktop audio software can have very advanced
capabilities, some of which would be difficult or impossible to build
with this system. Apple's Logic Audio is one such application which has
support for external MIDI controllers, arbitrary plugin audio effects
and synthesizers, highly optimized direct-to-disk audio file
reading/writing, tightly integrated time-stretching, and so on.
Nevertheless, the proposed system will be quite capable of supporting a
large range of reasonably complex games and interactive applications,
including musical ones. And it can be a very good complement to the
more advanced graphics features offered by WebGL. The API has been
designed so that more advanced capabilities can be added at a later
time.
<h3 id="Features">
Features</h3>
The API supports these primary features:
* [[#ModularRouting|Modular routing]] for simple or complex
mixing/effect architectures.
* High dynamic range, using 32-bit floats for internal processing.
* [[#AudioParam|Sample-accurate scheduled sound playback]]
with low [[#latency|latency]] for musical applications
requiring a very high degree of rhythmic precision such as drum
machines and sequencers. This also includes the possibility of
[[#DynamicLifetime|dynamic creation]] of effects.
* Automation of audio parameters for envelopes, fade-ins /
fade-outs, granular effects, filter sweeps, LFOs etc.
* Flexible handling of channels in an audio stream, allowing them
to be split and merged.
* Processing of audio sources from an <{audio}> or <{video}>
{{MediaElementAudioSourceNode|media element}}.
* Processing live audio input using a {{MediaStreamTrackAudioSourceNode|MediaStream}} from
{{getUserMedia()}}.
* Integration with WebRTC
* Processing audio received from a remote peer using a
{{MediaStreamTrackAudioSourceNode}} and
[[!webrtc]].
* Sending a generated or processed audio stream to a remote
peer using a {{MediaStreamAudioDestinationNode}}
and [[!webrtc]].
* Audio stream synthesis and processing [[#AudioWorklet|directly using scripts]].
* [[#Spatialization|Spatialized audio]] supporting a wide
range of 3D games and immersive environments:
* Panning models: equalpower, HRTF, pass-through
* Distance Attenuation
* Sound Cones
* Obstruction / Occlusion
* Source / Listener based
* A convolution engine for a wide
range of linear effects, especially very high-quality room effects.
Here are some examples of possible effects:
* Small / large room
* Cathedral
* Concert hall
* Cave
* Tunnel
* Hallway
* Forest
* Amphitheater
* Sound of a distant room through a doorway
* Extreme filters
* Strange backwards effects
* Extreme comb filter effects
* Dynamics compression for overall control and sweetening of the mix
* Efficient [[#AnalyserNode|real-time time-domain and frequency-domain analysis / music visualizer support]].
* Efficient biquad filters for lowpass, highpass, and other common filters.
* A Waveshaping effect for distortion and other non-linear effects
* Oscillators
<h4 id="ModularRouting">
Modular Routing</h4>
Modular routing allows arbitrary connections between different
{{AudioNode}} objects. Each node can have
<dfn>inputs</dfn> and/or <dfn>outputs</dfn>.
A <dfn>source node</dfn> has no inputs and a single output.
A <dfn>destination node</dfn> has one input and no outputs. Other nodes such as
filters can be placed between the source and destination nodes. The
developer doesn't have to worry about low-level stream format
details when two objects are connected together;
<a href="#channel-up-mixing-and-down-mixing">the right thing just happens</a>.
For example, if a mono audio stream is connected to a
stereo input it should just mix to left and right channels
[[#channel-up-mixing-and-down-mixing|appropriately]].
In the simplest case, a single source can be routed directly to the output.
All routing occurs within an {{AudioContext}}
containing a single {{AudioDestinationNode}}:
<figure>
<img alt="modular routing" src="images/modular-routing1.png" width="305" height="128">
<figcaption>
A simple example of modular routing.
</figcaption>
</figure>
Illustrating this simple routing, here's a simple example playing a single sound:
<pre class="example" highlight="js">
const context = new AudioContext();
function playSound() {
const source = context.createBufferSource();
source.buffer = dogBarkingBuffer;
source.connect(context.destination);
source.start(0);
}
</pre>
Here's a more complex example with three sources and a convolution
reverb send with a dynamics compressor at the final output stage:
<figure>
<img alt="modular routing2" src="images/modular-routing2.png" width="561" height="411">
<figcaption>
A more complex example of modular routing.
</figcaption>
</figure>
<pre class="example" highlight="js" line-numbers>
let context;
let compressor;
let reverb;
let source1, source2, source3;
let lowpassFilter;
let waveShaper;
let panner;
let dry1, dry2, dry3;
let wet1, wet2, wet3;
let mainDry;
let mainWet;
function setupRoutingGraph () {
context = new AudioContext();
// Create the effects nodes.
lowpassFilter = context.createBiquadFilter();
waveShaper = context.createWaveShaper();
panner = context.createPanner();
compressor = context.createDynamicsCompressor();
reverb = context.createConvolver();
// Create main wet and dry.
mainDry = context.createGain();
mainWet = context.createGain();
// Connect final compressor to final destination.
compressor.connect(context.destination);
// Connect main dry and wet to compressor.
mainDry.connect(compressor);
mainWet.connect(compressor);
// Connect reverb to main wet.
reverb.connect(mainWet);
// Create a few sources.
source1 = context.createBufferSource();
source2 = context.createBufferSource();
source3 = context.createOscillator();
source1.buffer = manTalkingBuffer;
source2.buffer = footstepsBuffer;
source3.frequency.value = 440;
// Connect source1
dry1 = context.createGain();
wet1 = context.createGain();
source1.connect(lowpassFilter);
lowpassFilter.connect(dry1);
lowpassFilter.connect(wet1);
dry1.connect(mainDry);
wet1.connect(reverb);
// Connect source2
dry2 = context.createGain();
wet2 = context.createGain();
source2.connect(waveShaper);
waveShaper.connect(dry2);
waveShaper.connect(wet2);
dry2.connect(mainDry);
wet2.connect(reverb);
// Connect source3
dry3 = context.createGain();
wet3 = context.createGain();
source3.connect(panner);
panner.connect(dry3);
panner.connect(wet3);
dry3.connect(mainDry);
wet3.connect(reverb);
// Start the sources now.
source1.start(0);
source2.start(0);
source3.start(0);
}
</pre>
Modular routing also permits the output of
{{AudioNode}}s to be routed to an
{{AudioParam}} parameter that controls the behavior
of a different {{AudioNode}}. In this scenario, the
output of a node can act as a modulation signal rather than an
input signal.
<figure>
<img alt="modular routing3" src="images/modular-routing3.png"
width="346" height="337">
<figcaption>
Modular routing illustrating one Oscillator modulating the
frequency of another.
</figcaption>
</figure>
<pre class="example" highlight="js" line-numbers>
function setupRoutingGraph() {
const context = new AudioContext();
// Create the low frequency oscillator that supplies the modulation signal
const lfo = context.createOscillator();
lfo.frequency.value = 1.0;
// Create the high frequency oscillator to be modulated
const hfo = context.createOscillator();
hfo.frequency.value = 440.0;
// Create a gain node whose gain determines the amplitude of the modulation signal
const modulationGain = context.createGain();
modulationGain.gain.value = 50;
// Configure the graph and start the oscillators
lfo.connect(modulationGain);
modulationGain.connect(hfo.detune);
hfo.connect(context.destination);
hfo.start(0);
lfo.start(0);
}
</pre>
<h3 id="APIOverview">
API Overview</h3>
The interfaces defined are:
* An <a class="dfnref" href="#AudioContext">AudioContext</a>
interface, which contains an audio signal graph representing
connections between {{AudioNode}}s.
* An {{AudioNode}} interface, which represents
audio sources, audio outputs, and intermediate processing modules.
{{AudioNode}}s can be dynamically connected together
in a [[#ModularRouting|modular fashion]].
{{AudioNode}}s exist in the context of an
{{AudioContext}}.
* An {{AnalyserNode}} interface, an
{{AudioNode}} for use with music visualizers, or
other visualization applications.
* An {{AudioBuffer}} interface, for working with
memory-resident audio assets. These can represent one-shot sounds, or
longer audio clips.
* An {{AudioBufferSourceNode}} interface, an
{{AudioNode}} which generates audio from an
AudioBuffer.
* An {{AudioDestinationNode}} interface, an
{{AudioNode}} subclass representing the final
destination for all rendered audio.
* An {{AudioParam}} interface, for controlling an
individual aspect of an {{AudioNode}}'s functioning,
such as volume.
* An {{AudioListener}} interface, which works with
a {{PannerNode}} for spatialization.
* An {{AudioWorklet}} interface representing a
factory for creating custom nodes that can process audio directly
using scripts.
* An {{AudioWorkletGlobalScope}} interface, the
context in which AudioWorkletProcessor processing scripts run.
* An {{AudioWorkletNode}} interface, an
{{AudioNode}} representing a node processed in an
AudioWorkletProcessor.
* An {{AudioWorkletProcessor}} interface,
representing a single node instance inside an audio worker.
* A {{BiquadFilterNode}} interface, an
{{AudioNode}} for common low-order filters such as:
* Low Pass
* High Pass
* Band Pass
* Low Shelf
* High Shelf
* Peaking
* Notch
* Allpass
* A {{ChannelMergerNode}} interface, an
{{AudioNode}} for combining channels from multiple
audio streams into a single audio stream.
* A {{ChannelSplitterNode}} interface, an {{AudioNode}} for accessing the individual channels of an
audio stream in the routing graph.
* A {{ConstantSourceNode}} interface, an
{{AudioNode}} for generating a nominally constant output value
with an {{AudioParam}} to allow automation of the value.
* A {{ConvolverNode}} interface, an
{{AudioNode}} for applying a
real-time linear effect (such as the sound of
a concert hall).
* A {{DelayNode}} interface, an
{{AudioNode}} which applies a dynamically adjustable
variable delay.
* A {{DynamicsCompressorNode}} interface, an
{{AudioNode}} for dynamics compression.
* A {{GainNode}} interface, an
{{AudioNode}} for explicit gain control.
* An {{IIRFilterNode}} interface, an
{{AudioNode}} for a general IIR filter.
* A {{MediaElementAudioSourceNode}} interface, an
{{AudioNode}} which is the audio source from an
<{audio}>, <{video}>, or other media element.
* A {{MediaStreamAudioSourceNode}} interface, an
{{AudioNode}} which is the audio source from a
{{MediaStream}} such as live audio input, or from a remote peer.
* A {{MediaStreamTrackAudioSourceNode}} interface,
an {{AudioNode}} which is the audio source from a
{{MediaStreamTrack}}.
* A {{MediaStreamAudioDestinationNode}} interface,
an {{AudioNode}} which is the audio destination to a
{{MediaStream}} sent to a remote peer.
* A {{PannerNode}} interface, an
{{AudioNode}} for spatializing / positioning audio in
3D space.
* A {{PeriodicWave}} interface for specifying
custom periodic waveforms for use by the
{{OscillatorNode}}.
* An {{OscillatorNode}} interface, an
{{AudioNode}} for generating a periodic waveform.
* A {{StereoPannerNode}} interface, an
{{AudioNode}} for equal-power positioning of audio
input in a stereo stream.
* A {{WaveShaperNode}} interface, an
{{AudioNode}} which applies a non-linear waveshaping
effect for distortion and other more subtle warming effects.
There are also several features that have been deprecated from the
Web Audio API but not yet removed, pending implementation experience
of their replacements:
* A {{ScriptProcessorNode}} interface, an {{AudioNode}} for generating or processing audio directly
using scripts.
* An {{AudioProcessingEvent}} interface, which is
an event type used with {{ScriptProcessorNode}}
objects.
<h2 id="audioapi">
The Audio API</h2>
<!--
████████ ███ ██████ ████████ ███ ██████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
████████ ██ ██ ██████ ██████ ██ ██ ██
██ ██ █████████ ██ ██ █████████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
████████ ██ ██ ██████ ████████ ██ ██ ██████
-->
<h3 interface lt="BaseAudioContext" id="BaseAudioContext">
The {{BaseAudioContext}} Interface</h3>
This interface represents a set of {{AudioNode}}
objects and their connections. It allows for arbitrary routing of
signals to an {{AudioDestinationNode}}. Nodes are
created from the context and are then [[#ModularRouting|connected]] together.
{{BaseAudioContext}} is not instantiated directly,
but is instead extended by the concrete interfaces
{{AudioContext}} (for real-time rendering) and
{{OfflineAudioContext}} (for offline rendering).
{{BaseAudioContext}} are created with an internal slot
<dfn attribute for="BaseAudioContext">[[pending promises]]</dfn> that is an
initially empty ordered list of promises.
Each {{BaseAudioContext}} has a unique
<a href="https://html.spec.whatwg.org/multipage/media.html#media-element-event-task-source">
media element event task source</a>.
Additionally, a {{BaseAudioContext}} has two private slots <dfn attribute
for="BaseAudioContext">[[rendering thread state]]</dfn> and <dfn attribute
for="BaseAudioContext">[[control thread state]]</dfn> that take values from
{{AudioContextState}}, and that are both
<div class="correction proposed" id="c2373-1">
<span class="marker">Proposed Correction
<a href="https://github.com/WebAudio/web-audio-api/issues/2373">Issue 2373</a>-1.
</span>
Use new Web IDL buffer primitives
<div class="amendment-buttons">
Buttons here
</div>
<del>initialy</del>
<ins>initially</ins>
</div>
set to <code>"suspended"</code>.
<pre class="idl">
enum AudioContextState {
"suspended",
"running",
"closed"
};
</pre>
<div class="enum-description">
<table class="simple" dfn-for="AudioContextState" dfn-type="enum-value">
<thead>
<tr>
<th scope="col" colspan="2">
Enumeration description
<tbody>
<tr>
<td>
"<dfn>suspended</dfn>"
<td>
This context is currently suspended (context time is not
proceeding, audio hardware may be powered down/released).
<tr>
<td>
"<dfn>running</dfn>"
<td>
Audio is being processed.
<tr>
<td>
"<dfn>closed</dfn>"
<td>
This context has been released, and can no longer be used to
process audio. All system audio resources have been released.
</table>
</div>
<xmp class="idl">
callback DecodeErrorCallback = undefined (DOMException error);
callback DecodeSuccessCallback = undefined (AudioBuffer decodedData);
[Exposed=Window]
interface BaseAudioContext : EventTarget {
readonly attribute AudioDestinationNode destination;
readonly attribute float sampleRate;
readonly attribute double currentTime;
readonly attribute AudioListener listener;
readonly attribute AudioContextState state;
[SameObject, SecureContext]
readonly attribute AudioWorklet audioWorklet;
attribute EventHandler onstatechange;
AnalyserNode createAnalyser ();
BiquadFilterNode createBiquadFilter ();
AudioBuffer createBuffer (unsigned long numberOfChannels,
unsigned long length,
float sampleRate);
AudioBufferSourceNode createBufferSource ();
ChannelMergerNode createChannelMerger (optional unsigned long numberOfInputs = 6);
ChannelSplitterNode createChannelSplitter (
optional unsigned long numberOfOutputs = 6);
ConstantSourceNode createConstantSource ();
ConvolverNode createConvolver ();
DelayNode createDelay (optional double maxDelayTime = 1.0);
DynamicsCompressorNode createDynamicsCompressor ();
GainNode createGain ();
IIRFilterNode createIIRFilter (sequence<double> feedforward,
sequence<double> feedback);
OscillatorNode createOscillator ();
PannerNode createPanner ();
PeriodicWave createPeriodicWave (sequence<float> real,
sequence<float> imag,
optional PeriodicWaveConstraints constraints = {});
ScriptProcessorNode createScriptProcessor(
optional unsigned long bufferSize = 0,
optional unsigned long numberOfInputChannels = 2,
optional unsigned long numberOfOutputChannels = 2);
StereoPannerNode createStereoPanner ();
WaveShaperNode createWaveShaper ();
Promise<AudioBuffer> decodeAudioData (
ArrayBuffer audioData,
optional DecodeSuccessCallback? successCallback,
optional DecodeErrorCallback? errorCallback);
};
</xmp>
<h4 id='BaseAudioContext-attributes'>
Attributes</h4>
<dl dfn-type=attribute dfn-for=BaseAudioContext>
: <dfn>audioWorklet</dfn>
::
Allows access to the <code>Worklet</code> object that can import
a script containing {{AudioWorkletProcessor}}
class definitions via the algorithms defined by [[!HTML]]
and {{AudioWorklet}}.
: <dfn>currentTime</dfn>
::
This is the time in seconds of the sample frame immediately
following the last sample-frame in the block of audio most
recently processed by the context's rendering graph. If the
context's rendering graph has not yet processed a block of
audio, then {{BaseAudioContext/currentTime}} has a value of
zero.
In the time coordinate system of {{BaseAudioContext/currentTime}}, the value of
zero corresponds to the first sample-frame in the first block
processed by the graph. Elapsed time in this system corresponds
to elapsed time in the audio stream generated by the
{{BaseAudioContext}}, which may not be
synchronized with other clocks in the system. (For an
{{OfflineAudioContext}}, since the stream is
not being actively played by any device, there is not even an
approximation to real time.)
All scheduled times in the Web Audio API are relative to the
value of {{BaseAudioContext/currentTime}}.
When the {{BaseAudioContext}} is in the
"{{AudioContextState/running}}" state, the
value of this attribute is monotonically increasing and is
updated by the rendering thread in uniform increments,
corresponding to one <a>render quantum</a>. Thus, for a running
context, <code>currentTime</code> increases steadily as the
system processes audio blocks, and always represents the time
of the start of the next audio block to be processed. It is
also the earliest possible time when any change scheduled in
the current state might take effect.
<code>currentTime</code> MUST be read <a>atomically</a> on the control thread before being
returned.
: <dfn>destination</dfn>
::
An {{AudioDestinationNode}}
with a single input representing the final destination for all
audio. Usually this will represent the actual audio hardware.
All {{AudioNode}}s actively rendering audio
will directly or indirectly connect to {{BaseAudioContext/destination}}.
: <dfn>listener</dfn>
::
An {{AudioListener}}
which is used for 3D <a href="#Spatialization">spatialization</a>.
: <dfn>onstatechange</dfn>
::
A property used to set the <code>EventHandler</code> for an
event that is dispatched to
{{BaseAudioContext}} when the state of the
AudioContext has changed (i.e. when the corresponding promise
would have resolved). An event of type
{{Event}} will be dispatched to the event
handler, which can query the AudioContext's state directly. A
newly-created AudioContext will always begin in the
<code>suspended</code> state, and a state change event will be
fired whenever the state changes to a different state. This
event is fired before the {{oncomplete}} event
is fired.
: <dfn>sampleRate</dfn>
::
The sample rate (in sample-frames per second) at which the
{{BaseAudioContext}} handles audio. It is assumed that all
{{AudioNode}}s in the context run at this rate. In making this
assumption, sample-rate converters or "varispeed" processors are
not supported in real-time processing.
The <dfn dfn for="/">Nyquist frequency</dfn> is half this sample-rate value.
: <dfn>state</dfn>
::
Describes the current state of the {{BaseAudioContext}}. Getting this
attribute returns the contents of the {{[[control thread state]]}} slot.
</dl>
<h4 id="BaseAudioContent-methods">
Methods</h4>
<dl dfn-type=method dfn-for=BaseAudioContext>
: <dfn>createAnalyser()</dfn>
::
<a>Factory method</a> for an {{AnalyserNode}}.
<div>
<em>No parameters.</em>
</div>
<div>
<em>Return type:</em> {{AnalyserNode}}
</div>
: <dfn>createBiquadFilter()</dfn>
::
<a>Factory method</a> for a {{BiquadFilterNode}}
representing a second order filter which can be configured as one
of several common filter types.
<div>
<em>No parameters.</em>
</div>
<div>
<em>Return type:</em> {{BiquadFilterNode}}
</div>
: <dfn>createBuffer(numberOfChannels, length, sampleRate)</dfn>
::
Creates an AudioBuffer of the given size. The audio data in the
buffer will be zero-initialized (silent).
<span class="synchronous">A {{NotSupportedError}} exception MUST be
thrown if any of the arguments is negative, zero, or outside its
nominal range.</span>
<pre class=argumentdef for="BaseAudioContext/createBuffer()">
numberOfChannels: Determines how many channels the buffer will have. An implementation MUST support at least 32 channels.
length: Determines the size of the buffer in sample-frames. This MUST be at least 1.
sampleRate: Describes the sample-rate of the [=linear PCM=] audio data in the buffer in sample-frames per second. An implementation MUST support sample rates in at least the range 8000 to 96000.
</pre>
<div>
<em>Return type:</em> {{AudioBuffer}}
</div>