Skip to content

Instantly share code, notes, and snippets.

@jakiestfu
Created April 1, 2024 15:57
Show Gist options
  • Save jakiestfu/f33c92f5da33c03782de26ad8a6626dc to your computer and use it in GitHub Desktop.
Save jakiestfu/f33c92f5da33c03782de26ad8a6626dc to your computer and use it in GitHub Desktop.
function trimSilenceFromBuffer(buffer, threshold = 0.001, minSilenceDuration = 0.1) {
const sampleRate = Tone.context.sampleRate;
const channelData = buffer.getChannelData(0); // Assuming mono audio for simplicity
let endOfAudioIndex = channelData.length - 1;
let silenceDuration = 0;
// Iterate backwards through the buffer
for (let i = channelData.length - 1; i >= 0; i--) {
const sample = Math.abs(channelData[i]); // Get the absolute value of the sample
if (sample <= threshold) {
silenceDuration += 1 / sampleRate;
if (silenceDuration >= minSilenceDuration) {
endOfAudioIndex = i + (silenceDuration * sampleRate);
break;
}
} else {
silenceDuration = 0; // Reset if the sample is above the threshold
}
}
// Trim the buffer
const trimmedLength = endOfAudioIndex + 1;
const trimmedBuffer = new Tone.Buffer(trimmedLength);
const trimmedChannelData = trimmedBuffer.getChannelData(0);
for (let i = 0; i < trimmedLength; i++) {
trimmedChannelData[i] = channelData[i];
}
return trimmedBuffer;
}
const trimmedBuffer = trimSilenceFromBuffer(buffer, 0.001, 0.1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment