Body.arrayBuffer()

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

The arrayBuffer() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.

Syntax

JavaScript
response.arrayBuffer().then(function(buffer) {
  // do something with buffer
});

Parameters

None.

Returns

A promise that resolves with an ArrayBuffer.

Example

In our fetch array buffer example (run fetch array buffer live), we have a Play button. When pressed, the getData() function is run.

In getData() we create a new request using the Request.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.)

JavaScript
function getData() {
  source = audioCtx.createBufferSource();

  var myRequest = new Request('viper.ogg');

  fetch(myRequest).then(function(response) {
    return response.arrayBuffer();
  }).then(function(buffer) {
    audioCtx.decodeAudioData(buffer, function(decodedData) {
      source.buffer = decodedData;
      source.connect(audioCtx.destination);
    });
  });
};

// wire up buttons to stop and play audio

play.onclick = function() {
  getData();
  source.start(0);
  play.setAttribute('disabled', 'disabled');
}

Specifications

Specification Status Comment
Fetch
The definition of 'arrayBuffer()' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 41[1]
42
 
34[1]
39 (39)
No support

28[1]
29

No support
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support No support No support No support No support No support No support No support

[1] In Chrome 42, Firefox 34 and Opera 28 support for arrayBuffer() was hidden behind a preference.

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/body/arraybuffer

API ArrayBuffer BODY Experimental Expérimental Fetch Method Reference Référence