Response: arrayBuffer() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
Note: This feature is available inWeb Workers.
ThearrayBuffer() method of theResponse interfacetakes aResponse stream and reads it to completion. It returns a promisethat resolves with anArrayBuffer.
In this article
Syntax
arrayBuffer()Parameters
None.
Return value
A promise that resolves with anArrayBuffer.
Exceptions
AbortErrorDOMExceptionThe request wasaborted.
TypeErrorThrown for one of the following reasons:
- The response body isdisturbed or locked.
- There was an error decoding the body content (for example, because the
Content-Encodingheader is incorrect).
RangeErrorThrown if there is a problem creating the associated
ArrayBuffer(for example, if the data size is too large).
Examples
>Playing music
In ourfetch array buffer live, we have a Play button. When pressed, thegetData()function is run. Note that before playing full audio file will be downloaded. If youneed to play ogg during downloading (stream it) - considerHTMLAudioElement:
new Audio("music.ogg").play();IngetData() we create a new request using theRequest() constructor, then use it to fetch an OGGmusic track. We also useAudioContext.createBufferSource to create anaudio buffer source. When the fetch is successful, we read anArrayBufferout of the response usingarrayBuffer(), decode the audio data usingAudioContext.decodeAudioData(), set the decoded data as the audio buffersource's buffer (source.buffer), then connect the source up to theAudioContext.destination.
OncegetData() has finished running, we start the audio source playingwithstart(0), then disable the play button so it can't be clicked againwhen 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 audioplay.onclick = () => { getData().then((source) => { source.start(0); play.setAttribute("disabled", "disabled"); });};Reading files
TheResponse() constructor acceptsFiles andBlobs, so it may be used to read aFile into other formats.
<input type="file" />function readFile(file) { return new Response(file).arrayBuffer();}document .querySelector("input[type=file]") .addEventListener("change", (event) => { const file = event.target.files[0]; const buffer = readFile(file); });Specifications
| Specification |
|---|
| Fetch> # ref-for-dom-body-arraybuffer①> |