Baseline Widely available
Note: This feature is available in Web Workers.
The arrayBuffer()
method of the Response
interface takes a Response
stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer
.
None.
Return valueA promise that resolves with an ArrayBuffer
.
DOMException
AbortError
The request was aborted.
TypeError
Thrown for one of the following reasons:
Content-Encoding
header is incorrect).RangeError
There was a problem creating the associated ArrayBuffer
. For example, if the data size is more than Number.MAX_SAFE_INTEGER
.
In our fetch array buffer live, we have a Play button. When pressed, the getData()
function is run. Note that before playing full audio file will be downloaded. If you need to play ogg during downloading (stream it) - consider HTMLAudioElement
:
new Audio("music.ogg").play();
In getData()
we create a new request using the Request()
constructor, then use it to fetch an OGG music track. We also use AudioContext.createBufferSource
to create an audio buffer source. When the fetch is successful, we read an ArrayBuffer
out of the response using arrayBuffer()
, decode the audio data using AudioContext.decodeAudioData()
, set the decoded data as the audio buffer source's buffer (source.buffer
), then connect the source up to the AudioContext.destination
.
Once getData()
has finished running, we start the audio source playing with start(0)
, then disable the play button so it can't be clicked again when it is already playing (this would cause an error.)
function getData() {
const audioCtx = new AudioContext();
return fetch("viper.ogg")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error, status = ${response.status}`);
}
return response.arrayBuffer();
})
.then((buffer) => audioCtx.decodeAudioData(buffer))
.then((decodedData) => {
const source = new AudioBufferSourceNode(audioCtx);
source.buffer = decodedData;
source.connect(audioCtx.destination);
return source;
});
}
// wire up buttons to stop and play audio
play.onclick = () => {
getData().then((source) => {
source.start(0);
play.setAttribute("disabled", "disabled");
});
};
Reading files
The Response()
constructor accepts File
s and Blob
s, so it may be used to read a File
into other formats.
function readFile(file) {
return new Response(file).arrayBuffer();
}
<input type="file" onchange="readFile(this.files[0])" />
Specifications Browser compatibility See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3