Skip to content

Instantly share code, notes, and snippets.

@praveenpuglia
Last active July 13, 2024 04:24
Show Gist options
  • Save praveenpuglia/61a296064815f19f391f2c84f12f134b to your computer and use it in GitHub Desktop.
Save praveenpuglia/61a296064815f19f391f2c84f12f134b to your computer and use it in GitHub Desktop.
Download Audio from AJAX and Play as Blob
// Updated on 16th May, 2024 based on @chamie's suggestion.
const response = await fetch("http://path/to/audio.wav");
const data = await response.arrayBuffer();
const blob = new Blob([data], { type: "audio/wav" });
const blobUrl = URL.createObjectURL(blob);
const audio = new Audio();
audio.src = blobUrl;
audio.controls = true;
document.body.appendChild(audio);
// Optionally, if you want to start playing right away:
audio.play();
@chamie
Copy link

chamie commented May 15, 2024

@yairMoshkovitz that's because this snippet uses the reader in a wrong way, one .read() call only gives you a ≈4k bytes chunk.

Here's how you could do it in 2024:

const response = await fetch("http://path/to/audio.wav");
const data = await response.arrayBuffer();
const blob = new Blob([data], { type: "audio/wav" });
const blobUrl = URL.createObjectURL(blob);
const audio = new Audio();
audio.src = blobUrl;
audio.controls = true;
document.body.appendChild(audio);
//Optionally, if you want to start playing right away:
audio.play();

@praveenpuglia
Copy link
Author

Thanks @chamie. Updating the code with your suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment