JSFiddle - React, Tailwind, and code Playground
JavaScript
// Duration of the
// change this value for a longer/shorter progressive volume decrease
let STOP_DURATION = 0.3; // 300 ms
//****************
let url = "https://raw.githubusercontent.com/gleitz/midi-js-soundfonts/gh-pages/MusyngKite/acoustic_guitar_steel-mp3/A4.mp3";
let soundContainer = {};
let notesMap = {"A4": [] };
let _AudioContext_ = AudioContext || webkitAudioContext;
let audioContext = new _AudioContext_();
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
makeLoop(arrayBuffer);
};
oReq.send(null);
function makeLoop(arrayBuffer){
soundContainer["A4"] = arrayBuffer;
let currentTime = audioContext.currentTime;
play("A4", currentTime);
}
function play(notePlayed, start, stopTime) {
audioContext.decodeAudioData(soundContainer[notePlayed], (buffer) => {
let source;
let gainNode;
source = audioContext.createBufferSource();
gainNode = audioContext.createGain();
// pushing notes in note map
notesMap[notePlayed].push({ source, gainNode });
source.buffer = buffer;
source.connect(gainNode);
gainNode.connect(audioContext.destination);
gainNode.gain.value = 1;
gainNode.gain.setValueAtTime(1, audioContext.currentTime + 0.5);
gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.5 + STOP_DURATION);
source.start(start);
});
}