Audio Buffer
by ShaCP
HTML
<div id="box1" class="box">
</div>
<div id="box2" class="box">
</div>
<script type="module">
import sac from 'https://jspm.dev/standardized-audio-context';
window.decodeAudioData = sac.decodeAudioData;
</script>
CSS
#box1 {
background-color: lightblue;
}
#box2 {
background-color: lightyellow;
}
.box {
width: 100px;
height: 100px;
}
JavaScript
window.onload = () => {
debugger;
/* import {
decodeAudioData
} from 'https://jspm.dev/standardized-audio-context'; */
const audioURL = 'https://freesound.org/data/previews/51/51702_113976-lq.mp3'
const audioURL2 = 'https://freesound.org/data/previews/351/351369_4603244-lq.mp3'
const functions = [
function() {
this.playback(0)
},
function() {
this.playback(1)
}
]
class AudioBuffer {
constructor(urls) {
this.audioContext = new window.AudioContext();
this.urls = urls;
this.buffers = [];
this.audioTracks = [];
functions.forEach((func, i) => {
this[`play${i}`] = func.bind(this);
});
}
async loadSound(url, index) {
const thisBuffer = this;
const {
urls,
buffers,
loaded,
audioContext
} = thisBuffer;
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await decodeAudioData(audioContext, arrayBuffer);
buffers[index] = audioBuffer;
if (index === urls.length - 1) {
this.loaded();
}
}
loadAll() {
const {
urls,
loadSound
} = this;
urls.forEach((url, index) => {
this.loadSound(url, index);
});
}
unlockAudioContext() {
const {
audioContext: {
state,
resume
},
} = this;
if (state !== "suspended") return;
const {
body
} = document;
const eventTypes = ["touchstart", "touchend", "mousedown", "keydown"];
eventTypes.forEach((eventType) =>
body.addEventListener(eventType, unlock, false)
);
async function unlock() {
await resume();
clean();
}
function clean() {
eventTypes.forEach((eventType) =>
body.removeEventListener(eventType, unlock)
);
}
}
loaded(callback) {
// what happens when all...