Last active
March 9, 2020 22:26
-
-
Save wilforlan/a6d13510fd8a67406a69925b349d4437 to your computer and use it in GitHub Desktop.
Get the Silence Information of an audio file.
This file contains 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
const fs = require('fs'); | |
const readline = require('readline'); | |
const { exec } = require('child_process'); | |
let MATCH_REGEX = /silence_end.*|silence_start.*/gm | |
const findSilenceParts = (stream, callback, options = {}) => { | |
return new Promise((resolve, reject) => { | |
let { overrideRegex } = options | |
let matches = []; | |
let duration = null; | |
var lineReader = readline.createInterface({ | |
input: stream | |
}); | |
lineReader.on('line', function (line) { | |
let match = line.match(overrideRegex || MATCH_REGEX); | |
if(!duration) duration = line.match(/Duration: (\d\d):(\d\d):(\d\d(\.\d\d)?)/g); | |
if(match) matches.push(match[0]); | |
}); | |
lineReader.on('close', () => { | |
resolve({ matches, duration: (duration && duration[0] && duration[0].split('Duration: '))[1]}); // find a better way get duration | |
}); | |
}) | |
}; | |
const getLogPath = (file, find, replace) => { | |
let lk = file.split('/'); | |
let logPath = lk[lk.length - 1]; | |
return logPath.replace(find, replace); | |
}; | |
const rm = (file) => { | |
fs.unlink(file, (err) => { | |
if(err) { console.log(err) } | |
else { console.log(`Remove file: ${file}`)} | |
}); | |
}; | |
const getSilenceInFile = (inputFile, useLog = null) => { | |
// ffmpeg -i /Users/wilforlan/Documents/Fireflies/voice-puppet-ff/store/TestWebSocketsFF-de07a7c5.mp3 -filter_complex "[0:a]silencedetect=n=-50dB:d=1[outa]" -map [outa] call-3.mp3 -y 2>&1 | cut -d 'l' -f 3 | cut -d ']' -f 2 | cut -d "|" -f 1 > log-2.txt | |
let logPath = getLogPath(inputFile, '.mp3', '-silencelog.log'); | |
let tempReWritePath = getLogPath(inputFile, '.mp3', '-temp.mp3'); | |
let cmd = `ffmpeg -i ${inputFile} -filter_complex "[0:a]silencedetect=n=-50dB:d=1[outa]" -map [outa] ${tempReWritePath} -y 2>&1 | cut -d ']' -f 2 | cut -d "|" -f 1 > ${logPath}`; | |
console.log({ cmd }); | |
return new Promise((resolve, reject) => { | |
if(useLog) return resolve(useLog); // testing purposes if you already have a log file | |
exec(cmd, (err, stdout) => { | |
if(err) reject(err); | |
rm(tempReWritePath); | |
resolve(logPath); | |
}); | |
}); | |
}; | |
const chunkArray = (arr, n) => { | |
return new Array(Math.ceil(arr.length / n)).fill("") | |
.map(function() { return this.splice(0, n) }, arr.slice()); | |
} | |
function sec2time(timeInSeconds) { | |
var pad = function(num, size) { return ('000' + num).slice(size * -1); }, | |
time = parseFloat(timeInSeconds).toFixed(3), | |
hours = Math.floor(time / 60 / 60), | |
minutes = Math.floor(time / 60) % 60, | |
seconds = Math.floor(time - minutes * 60), | |
milliseconds = time.slice(-3); | |
return pad(hours, 2) + ':' + pad(minutes, 2) + ':' + pad(seconds, 2) + '.' + pad(milliseconds, 2); | |
} | |
const buildFinalResults = (match) => { | |
return new Promise((resolve, reject) => { | |
let result = chunkArray(match, 2).map( innerArray => { | |
let silence_start = parseFloat(innerArray[0].split("silence_start: ")[1]); | |
let silence_end = parseFloat(innerArray[1].split("silence_end: ")[1]); | |
let diff = (silence_end - silence_start).toFixed(3); | |
return { | |
diff, | |
parsed: { | |
silence_start: sec2time(silence_start), | |
silence_end: sec2time(silence_end) | |
}, | |
raw: { | |
silence_start, | |
silence_end | |
} | |
} | |
}); | |
let totalSilenceDuration = result.reduce((acc, obj) => { | |
return acc + parseFloat(obj.diff) | |
}, 0.0); // in seconds | |
resolve({ result, totalSilenceDuration, totalSilenceDurationInMins: sec2time(totalSilenceDuration) }); | |
}) | |
}; | |
// Usage | |
(async () => { | |
try { | |
let log = await getSilenceInFile("https://somelink.mp3", "path-to-log/call-67243012-silencelog.log"); | |
let { matches, duration } = await findSilenceParts(fs.createReadStream(log)) | |
let response = await buildFinalResults(matches); | |
if(response) response.duration = duration | |
// rm(log); | |
console.log("%j", response) | |
// Check the comment section for a sample of the JSON Log and a sample log file. | |
} catch (error) { | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Audio Log