Created
January 20, 2018 18:53
-
-
Save jbodah/05489a58a67dc18925ee1cf5abc21e0e to your computer and use it in GitHub Desktop.
detecting audio edges for auto-trimming using the web audio api
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>audio edge test</title> | |
</head> | |
<body> | |
</body> | |
<script> | |
var audioCtx = new AudioContext(); | |
var audio = new Audio('file:///Users/jbodah/desktop/audio-edge-test.flac'); | |
var source = audioCtx.createMediaElementSource(audio); | |
var bandpass = audioCtx.createBiquadFilter(); | |
bandpass.type = 'bandpass'; | |
bandpass.frequency = 3700/2; | |
bandpass.Q.value = 100; | |
var analyser = audioCtx.createAnalyser(); | |
analyser.fftSize = 256; | |
var dataArray = new Uint8Array(analyser.frequencyBinCount); | |
var gainNode = audioCtx.createGain(); | |
gainNode.gain.value = 20; | |
function getVolume(arr) { | |
return arr.reduce((acc, n) => acc + n, 0) / arr.length; | |
} | |
// Edge Detection | |
var threshold = 1.5; | |
var firstEdge = null; | |
var lastEdge = null; | |
var sampleRate = 100; | |
setInterval(function () { | |
analyser.getByteFrequencyData(dataArray); | |
var volume = getVolume(dataArray); | |
if (volume > threshold) { | |
console.log(volume); | |
var pos = audio.currentTime; | |
if (firstEdge === null) | |
firstEdge = pos; | |
lastEdge = pos; | |
} | |
}, sampleRate); | |
audio.addEventListener("ended", function(){ | |
console.log("firstEdge: " + firstEdge); | |
console.log("lastEdge: " + lastEdge); | |
setTimeout(function () { | |
console.log("starting over"); | |
audio.currentTime = firstEdge - 0.3; | |
audio.play(); | |
var stopIn = Math.round((lastEdge - firstEdge) * 1000) + 1000; | |
setTimeout(function () { | |
audio.pause(); | |
}, stopIn); | |
}, 500); | |
}); | |
source.connect(bandpass); | |
bandpass.connect(analyser); | |
analyser.connect(gainNode); | |
source.connect(audioCtx.destination); | |
//gainNode.connect(audioCtx.destination); | |
audio.play(); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment