Skip to content

Instantly share code, notes, and snippets.

@evaletolab
Created April 29, 2023 12:49
Show Gist options
  • Save evaletolab/94d46501a8e159dd7125aa45fdc3f5e3 to your computer and use it in GitHub Desktop.
Save evaletolab/94d46501a8e159dd7125aa45fdc3f5e3 to your computer and use it in GitHub Desktop.
//
// ensure that recorded mp3 contains audio
// - https://stackoverflow.com/questions/71103807/detect-silence-in-audio-recording
async detectSound(content) {
const MIN_DECIBELS = -45;
const audioCtx:AudioContext = new(window.AudioContext || (<any>window).webkitAudioContext)();
const blobUrl = (content.blob)?URL.createObjectURL(content.blob):content.url;
const audio = new Audio();
audio.playbackRate=2;
audio.src = blobUrl;
audio.volume = 0;
const audioSource:MediaElementAudioSourceNode = audioCtx.createMediaElementSource(audio);
// Create an analyser
const analyser = audioCtx.createAnalyser();
analyser.minDecibels = MIN_DECIBELS;
audioSource.connect(analyser);
const bufferLength = analyser.frequencyBinCount;
const domainData = new Uint8Array(bufferLength);
// Connect parts to get audio buffer
analyser.connect(audioCtx.destination);
await audio.play();
return new Promise((resolve,reject)=> {
const processSound = () => {
analyser.getByteFrequencyData(domainData);
for (let i = 0; i < bufferLength; i++) {
if (domainData[i] > 0) {
return resolve(true);
}
}
window.requestAnimationFrame(processSound);
}
window.requestAnimationFrame(processSound);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment