I found a script on this forum at this link for looping an audio clip using the Web Audio API, and it works well, however I’m having problems working out how to control the volume of it. Apparently the key is to use “createGain”, but I’ve been having difficulties getting that to work. (I also tried the “Loopify” suggestion on that page, but Loopify doesn’t let you control the volume.)
See in the script where the comment says “START TRYING TO SET THE VOLUME”. I’m think I’m close with it, but it’s just not working. The sample is trying to reduce the volume to half.
// initialize the audio
var actx = new (AudioContext || webkitAudioContext)(), src="lo-fi-dub-beat_70bpm.wav", audioData, srcNode;
// load the audio
fetch(src, {mode: "cors"}).then(function(resp) {return resp.arrayBuffer()}).then(decode);
// START TRYING TO SET THE VOLUME
var loopAudioGainNode = actx.createGain();
loopAudioGainNode.connect(actx.destination); // <- Perhaps this is needed?
loopAudioGainNode.gain.value = .5;
// END TRYING TO SET THE VOLUME
// decode the audio and start it playing
function decode (buffer) { actx.decodeAudioData(buffer, playLoop); }
// set a new source node as needed after the audio was stopped
function playLoop (abuffer) {
if (!audioData) audioData = abuffer; // create a reference for control buttons
srcNode = actx.createBufferSource(); // create audio source
srcNode.buffer = abuffer; // use decoded buffer
srcNode.connect(actx.destination); // create output
srcNode.loop = true; // takes care of perfect looping
srcNode.start(); // play...
}
Thanks for your help.