From c058fa0fb22dc40ef0225b21a97578cddd0aaffa Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:51:05 +0100 Subject: unslug ru: move --- .../api/baseaudiocontext/createpanner/index.html | 211 ++++++++++++++++++++ .../api/baseaudiocontext/currenttime/index.html | 97 +++++++++ .../baseaudiocontext/decodeaudiodata/index.html | 220 +++++++++++++++++++++ 3 files changed, 528 insertions(+) create mode 100644 files/ru/web/api/baseaudiocontext/createpanner/index.html create mode 100644 files/ru/web/api/baseaudiocontext/currenttime/index.html create mode 100644 files/ru/web/api/baseaudiocontext/decodeaudiodata/index.html (limited to 'files/ru/web/api/baseaudiocontext') diff --git a/files/ru/web/api/baseaudiocontext/createpanner/index.html b/files/ru/web/api/baseaudiocontext/createpanner/index.html new file mode 100644 index 0000000000..0a4d5db32b --- /dev/null +++ b/files/ru/web/api/baseaudiocontext/createpanner/index.html @@ -0,0 +1,211 @@ +--- +title: AudioContext.createPanner() +slug: Web/API/AudioContext/createPanner +translation_of: Web/API/BaseAudioContext/createPanner +--- +

{{ APIRef("Web Audio API") }}

+ +
+

Метод createPanner() интерфейса {{ domxref("AudioContext") }} применяется для создания нового {{domxref("PannerNode")}}, который используется для размещения аудиопотока в виртуальном 3D пространстве.

+
+ +

The panner node is spatialized in relation to the AudioContext's {{domxref("AudioListener") }} (defined by the {{domxref("AudioContext.listener") }} attribute), which represents the position and orientation of the person listening to the audio.

+ +

Синтаксис

+ +
var audioCtx = new AudioContext();
+var panner = audioCtx.createPanner();
+ +

Возврат

+ +

A {{domxref("PannerNode")}}.

+ +

Пример

+ +
+
Ниже можно увидеть пример использования {{domxref("AudioListener")}}, {{domxref("PannerNode")}} и метода createPanner() для управления пространством объемного звука. Обычно определяется положение в трехмерном пространстве, изначально занимаемое слушателем (listener) и источником звука (panner), а затем, при использовании приложения, обновляется позиция одного из них или обоих. Например, вы можете перемещать персонажа внутри игрового мира, и желательно чтобы передача звука изменялась реалистично, по мере приближения или отдаления персонажа относительно источника звука, вроде стереопроигрывателя. В этом примере можно видеть, что все это управляется функциями moveRight(), moveLeft(), и т.п., которые устанавливают новые значения для положения паннера через функцию PositionPanner().
+ +
 
+ +
+
+
Чтобы увидеть полную реализацию ознакомьтесь с нашим примером panner-node (просмотрите весь список примеров) — эта демонстрация перенесет вас в 2.5D "Room of metal" (2,5-мерную "металлическую комнату"), где можно проиграть трек на бумбоксе и затем походить вокруг него и посмотреть как изменяется звук!
+ +
 
+
+
+
+ +

Note how we have used some feature detection to either give the browser the newer property values (like {{domxref("AudioListener.forwardX")}}) for setting position, etc. if it supports those, or older methods (like {{domxref("AudioListener.setOrientation()")}}) if it still supports those but not the new properties.

+ +
// set up listener and panner position information
+// установка сведений о слушателе (listener) и положении panner'а
+var WIDTH = window.innerWidth;
+var HEIGHT = window.innerHeight;
+
+var xPos = Math.floor(WIDTH/2);
+var yPos = Math.floor(HEIGHT/2);
+var zPos = 295;
+
+// define other variables (определяем другие переменные)
+
+var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var panner = audioCtx.createPanner();
+panner.panningModel = 'HRTF';
+panner.distanceModel = 'inverse';
+panner.refDistance = 1;
+panner.maxDistance = 10000;
+panner.rolloffFactor = 1;
+panner.coneInnerAngle = 360;
+panner.coneOuterAngle = 0;
+panner.coneOuterGain = 0;
+
+if(panner.orientationX) {
+  panner.orientationX.value = 1;
+  panner.orientationY.value = 0;
+  panner.orientationZ.value = 0;
+} else {
+  panner.setOrientation(1,0,0);
+}
+
+var listener = audioCtx.listener;
+
+if(listener.forwardX) {
+  listener.forwardX.value = 0;
+  listener.forwardY.value = 0;
+  listener.forwardZ.value = -1;
+  listener.upX.value = 0;
+  listener.upY.value = 1;
+  listener.upZ.value = 0;
+} else {
+  listener.setOrientation(0,0,-1,0,1,0);
+}
+
+var source;
+
+var play = document.querySelector('.play');
+var stop = document.querySelector('.stop');
+
+var boomBox = document.querySelector('.boom-box');
+
+var listenerData = document.querySelector('.listener-data');
+var pannerData = document.querySelector('.panner-data');
+
+leftBound = (-xPos) + 50;
+rightBound = xPos - 50;
+
+xIterator = WIDTH/150;
+
+// listener will always be in the same place for this demo
+// в этом демо слушатель всегда находится на одном и том же месте
+
+if(listener.positionX) {
+  listener.positionX.value = xPos;
+  listener.positionY.value = yPos;
+  listener.positionZ.value = 300;
+} else {
+  listener.setPosition(xPos,yPos,300);
+}
+
+listenerData.innerHTML = 'Listener data: X ' + xPos + ' Y ' + yPos + ' Z ' + 300;
+
+// panner will move as the boombox graphic moves around on the screen
+// паннер будет перемещаться по экрану за перемещением бумбокса
+function positionPanner() {
+  if(panner.positionX) {
+    panner.positionX.value = xPos;
+    panner.positionY.value = yPos;
+    panner.positionZ.value = zPos;
+  } else {
+    panner.setPosition(xPos,yPos,zPos);
+  }
+  pannerData.innerHTML = 'Panner data: X ' + xPos + ' Y ' + yPos + ' Z ' + zPos;
+}
+ +
+

In terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on screen, there is quite a bit of fiddly math involved, but you will soon get used to it with a bit of experimentation.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createPanner-PannerNode', 'createPanner()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

See also

+ + diff --git a/files/ru/web/api/baseaudiocontext/currenttime/index.html b/files/ru/web/api/baseaudiocontext/currenttime/index.html new file mode 100644 index 0000000000..51370701f4 --- /dev/null +++ b/files/ru/web/api/baseaudiocontext/currenttime/index.html @@ -0,0 +1,97 @@ +--- +title: AudioContext.currentTime +slug: Web/API/AudioContext/currentTime +translation_of: Web/API/BaseAudioContext/currentTime +--- +

{{ APIRef("AudioContext") }}

+
+

Поле currentTime принадлежит {{ domxref("AudioContext") }} и возвращает время с момента создания AudioContext. Может использоваться при планировании воспроизведения или визуализации.  Поле currentTime является не перезаписываемым и не может быть остановлено или сброшено.

+
+

Синтаксис

+
var audioCtx = new AudioContext();
+console.log(audioCtx.currentTime);
+

Тип данных

+

A double.

+

Примеры

+
+

Примечание: для большего понимания реализации Web Audio, посмотрите наши Web Audio Demos на MDN Github repo, like panner-node. Попробуйте ввести audioCtx.currentTime в консоли вашего браузера.

+
+
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// Older webkit/blink browsers require a prefix
+
+...
+
+console.log(audioCtx.currentTime);
+
+

Specifications

+ + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{Spec2('Web Audio API')}} 
+

Browser compatibility

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+

See also

+ diff --git a/files/ru/web/api/baseaudiocontext/decodeaudiodata/index.html b/files/ru/web/api/baseaudiocontext/decodeaudiodata/index.html new file mode 100644 index 0000000000..faae982eae --- /dev/null +++ b/files/ru/web/api/baseaudiocontext/decodeaudiodata/index.html @@ -0,0 +1,220 @@ +--- +title: AudioContext.decodeAudioData() +slug: Web/API/AudioContext/decodeAudioData +tags: + - API +translation_of: Web/API/BaseAudioContext/decodeAudioData +--- +

{{ APIRef("Web Audio API") }}

+ +
+

The decodeAudioData() method of the {{ domxref("AudioContext") }} Interface is used to asynchronously decode audio file data contained in an {{domxref("ArrayBuffer")}}. In this case the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s response attribute after setting the responseType to arraybuffer. The decoded AudioBuffer is resampled to the AudioContext's sampling rate, then passed to a callback or promise.

+
+ +

This is the preferred method of creating an audio source for Web Audio API from an audio track.

+ +

Syntax

+ +

Older callback syntax:

+ +
audioCtx.decodeAudioData(audioData, function(decodedData) {
+  // use the dec​oded data here
+});
+ +

Newer promise-based syntax:

+ +
audioCtx.decodeAudioData(audioData).then(function(decodedData) {
+  // use the decoded data here
+});
+ +

Example

+ +

In this section we will first cover the older callback-based system and then the newer promise-based syntax.

+ +

Older callback syntax

+ +

In this example, the getData() function uses XHR to load an audio track, setting the responseType of the request to arraybuffer so that it returns an array buffer as its response that we then store in the audioData variable . We then pass this buffer into a decodeAudioData() function; the success callback takes the successfully decoded PCM data, puts it into an {{ domxref("AudioBufferSourceNode") }} created using {{ domxref("AudioContext.createBufferSource()") }}, connects the source to the {{domxref("AudioContext.destination") }} and sets it to loop.

+ +

The buttons in the example simply run getData() to load the track and start it playing, and stop it playing, respectively. When the stop() method is called on the source, the source is cleared out.

+ +
+

Note: You can run the example live (or view the source.)

+
+ +
// define variables
+
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var source;
+
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+var play = document.querySelector('.play');
+var stop = document.querySelector('.stop');
+
+// use XHR to load an audio track, and
+// decodeAudioData to decode it and stick it in a buffer.
+// Then we put the buffer into the source
+
+function getData() {
+  source = audioCtx.createBufferSource();
+  var request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+        source.buffer = buffer;
+
+        source.connect(audioCtx.destination);
+        source.loop = true;
+      },
+
+      function(e){"Error with decoding audio data" + e.err});
+
+  }
+
+  request.send();
+}
+
+// wire up buttons to stop and play audio
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+
+stop.onclick = function() {
+  source.stop(0);
+  play.removeAttribute('disabled');
+}
+
+
+// dump script to pre element
+
+pre.innerHTML = myScript.innerHTML;
+ +

New promise-based syntax

+ +
ctx.decodeAudioData(compressedBuffer).then(function(decodedData) {
+ // use the decoded data here
+});
+ +

Parameters

+ +
+
ArrayBuffer
+
An ArrayBuffer containing the audio data to be decoded, usually grabbed from an {{domxref("XMLHttpRequest")}}'s response attribute after setting the responseType to arraybuffer.
+
DecodeSuccessCallback
+
A callback function to be invoked when the decoding successfully finishes. The single argument to this callback is an AudioBuffer representing the decoded PCM audio data. Usually you'll want to put the decoded data into an {{domxref("AudioBufferSourceNode")}}, from which it can be played and manipulated how you want.
+
DecodeErrorCallback
+
An optional error callback, to be invoked if an error occurs when the audio data is being decoded.
+
+ +

Returns

+ +

An {{domxref("AudioBuffer") }} representing the decoded PCM audio data.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-decodeAudioData-Promise-AudioBuffer--ArrayBuffer-audioData-DecodeSuccessCallback-successCallback-DecodeErrorCallback-errorCallback', 'decodeAudioData()')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
Promise-based syntax{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
Promise-based syntax{{CompatUnknown}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf