Forked from praveenpuglia/playAudioAsBlobViaAjax.js
Created
November 26, 2021 08:10
-
-
Save yeungon/2d1a728dc44e9533e9e730252f315b05 to your computer and use it in GitHub Desktop.
Download Audio from AJAX and Play as Blob
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = fetch("http://path/to/audio.wav") | |
.then(res => { | |
var reader = res.body.getReader(); | |
return reader.read().then(result => { | |
return result; | |
}); | |
}) | |
.then(data => { | |
console.log(data); | |
var blob = new Blob([data.value], { type: "audio/wav" }); | |
var blobUrl = URL.createObjectURL(blob); | |
window.audio = new Audio(); | |
window.audio.src = blobUrl; | |
window.audio.controls = true; | |
document.body.appendChild(window.audio); | |
}); |
`
<script> | |
// https://staxmanade.com/2015/11/how-to-base64-and-save-a-binary-audio-file-to-local-storage-and-play-it-back-in-the-browser/ | |
var audioFileUrl = 'https://dl.airtable.com/.attachments/04461bb6f9cf2f2b27407c86f4455708/a85d831d/y2matemp3cut.net4.mp3'; | |
window.onload = function() { | |
var downloadButton = document.getElementById('download'); | |
var audioControl = document.getElementById('audio'); | |
audioControl.onerror = function(){ | |
console.log(audioControl.error); | |
}; | |
downloadButton.addEventListener('click', function() { | |
audioControl.src = null; | |
fetch(audioFileUrl) | |
.then(function(res) { | |
res.blob().then(function(blob) { | |
var size = blob.size; | |
var type = blob.type; | |
var reader = new FileReader(); | |
reader.addEventListener("loadend", function() { | |
// console.log('reader.result:', reader.result); | |
// 1: play the base64 encoded data directly works | |
// audioControl.src = reader.result; | |
// 2: Serialize the data to localStorage and read it back then play... | |
var base64FileData = reader.result.toString(); | |
var mediaFile = { | |
fileUrl: audioFileUrl, | |
size: blob.size, | |
type: blob.type, | |
src: base64FileData | |
}; | |
// save the file info to localStorage | |
localStorage.setItem('myTest', JSON.stringify(mediaFile)); | |
// read out the file info from localStorage again | |
var reReadItem = JSON.parse(localStorage.getItem('myTest')); | |
audioControl.src = reReadItem.src; | |
}); | |
reader.readAsDataURL(blob); | |
}); | |
}); | |
}); | |
}; | |
</script> | |
Run Example | |
`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/40326823/javascript-make-audio-blob/40329529