-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathaudioutils.js
266 lines (215 loc) · 6.92 KB
/
audioutils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
const fs = require('fs')
const { spawn } = require('child_process')
const SAMPLE_RATE = 16000
const BUFFER_SIZE = 4000
/**
* ffmpegArgsToPCM
* set ffmpeg args to convert any source audio file/buffer to a PCM file/buffer
*
* @function
*
* @param {String} sourceFile
* @param {String} destinationFile
*
* @see https://stackoverflow.com/questions/45899585/pipe-input-in-to-ffmpeg-stdin
* @see https://ffmpeg.org/ffmpeg-protocols.html#pipe
*
* @param {Number} sampleRate
* @param {Number} bufferSize
*
* @return {String[]} array containing the list of arguments for ffmpeg cli program
*/
const ffmpegArgsToPCM = (sourceFile, sampleRate, bufferSize, destinationFile) => [
'-loglevel',
'quiet',
'-i', sourceFile,
'-ar', String(sampleRate),
'-ac', '1',
'-f', 's16le',
'-bufsize', String(bufferSize),
destinationFile
]
/**
* toPCM
*
* @function
* @async
* @requires ffmpeg installed in your host
*
* transcode (file or buffer) audio
* from an input file or an input Buffer to a PCM audio buffer
* spawning an external ffmpeg process.
*
* Input buffer is passed to ffmpeg child process, piping stream trough stdin
* Output buffer is piped by ffmpeg child process, piping stream to stdout
* This way, using stdin/stdout I/O you skip disk I/O, avoiding filesystem!
*
* @typedef {ToPCMObject}
* @property {String} sourceFile. pipe:0 means stdin
* @property {String} destinationFile. pipe:1 means stdout
* @property {Number} sampleRate
* @property {Number} bufferSize
*
* @param {ToPCMObject} ToPCMBufferObject
* @return {Promise<Buffer>}
*
* @example
* // 1. from an input Buffer to an output Buffer
* const sourceBuffer = ...
* toPCM( {sourceBuffer} )
*
* // 2. from an input Buffer to an output file
* const destinationFile = 'file.webm.wav'
* toPCM( {sourceBuffer, destinationFile} )
*
* // 3. from an input file to an output Buffer
* const sourceFile = "file.webm"
* toPCM( {sourceFile} )
*
* // 4. from an input file to an output file
* const sourceFile = "file.webm"
* toPCM( {sourceFile, destinationFile} )
*
*/
function toPCM({sourceBuffer=undefined, sourceFile='pipe:0', destinationFile='pipe:1', sampleRate=SAMPLE_RATE, bufferSize=BUFFER_SIZE} = {}) {
return new Promise( (resolve, reject) => {
//const ffmpegStart = new Date()
let ffmpeg
try {
ffmpeg = spawn('ffmpeg', ffmpegArgsToPCM(sourceFile, sampleRate, bufferSize, destinationFile))
}
catch (error) {
return reject(`ffmpeg spawn error: ${error}`)
}
//console.log(`ffmpeg command : ffmpeg ${ffmpegArgsToPCM.join(' ')}`)
/**
* if the source Buffer is specified, write it into ffmpeg process stdin avoiding disk I/O.
*
* @see
* https://stackoverflow.com/questions/30937751/pass-a-buffer-to-a-node-js-child-process
* https://stackoverflow.com/questions/30943250/pass-buffer-to-childprocess-node-js?noredirect=1&lq=1
*/
if (sourceBuffer)
ffmpeg.stdin.end(sourceBuffer)
//let bufferDataItem = 1
// allocate a buffer to contain PCM data collected from stdout
let buffer = Buffer.alloc(0)
ffmpeg.stdout.on('data', (stdout) => {
buffer = Buffer.concat([buffer, stdout])
//console.log()
//console.log(`data item : ${bufferDataItem++}`)
//console.log(`data size : ${stdout.length}`)
//console.log(`ffmpeg item latency : ${new Date() - ffmpegStart}ms`)
})
ffmpeg.on('close', () => resolve(buffer))
})
}
/**
* audio duration in seconds (of a pcm buffer)
*
* @function
* @public
*
* @see https://stackoverflow.com/questions/62553574/calculate-duration-of-arraybuffer-without-audio-api
*
* @param {Buffer} arrayBuffer
* @param {Number} numChannels
* @param {Number} sampleRate
* @param {Number} bytesPerSample
*
* @return {Number} duration in seconds
*
*/
function duration(arrayBuffer, numChannels=1, sampleRate=16000, bytesPerSample=2) {
// total samples/frames
const totalSamples = arrayBuffer.byteLength / bytesPerSample / numChannels
// total seconds
return totalSamples / sampleRate
}
/**
* Real-Time Factor
* Real-Time Factor (RTF) is defined as processing-time / length-of-audio.
* The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF.
*
* @param {Number} processingTime (secs)
* @param {Number} audioLength (secs)
* @param {Number} decimals number of decimals precision
* @return {Number} calculated value as floating number
*/
const rtf = (processingTime, audioLenght, decimals=2) =>
+((processingTime / audioLenght).toFixed(decimals))
/**
* aproxKiloBytes
* pretty print an audio length in KB
*
* @function
* @public
*
* @param {Number} duration
* @return {String}
*
* @example
* aproxKiloBytes(63345) // => '63345~63Kb'
*
*/
const aproxKiloBytes = (bytes) =>
`${bytes}~${Math.round(bytes / 1024)}K`
/**
* aproxSecs
* pretty print an audio duration in seconds
*
* @function
* @public
*
* @param {Number} duration
* @return {String}
*
* @example
* msecsSecs(1.23445678) // => '1234ms~1s'
*
*/
const aproxSecs = (duration) =>
`${Math.round(duration*1000)}ms~${Math.round(duration)}s`
const byteLength = (buffer) =>
buffer.byteLength
// test
async function main() {
const sourceFile = '../audio/2830-3980-0043.wav.webm'
/*
console.log()
console.log('TEST 1: ffmpeg arguments for PCM output ')
const args = toPCMffmpegArgs({sourceFile})
console.log(`ffmpeg command arguments: ffmpeg ${args.join(' ')}`)
*/
console.log()
console.log('TEST: input Buffer (any audio format), output Buffer (PCM format)')
console.log('-----------------------------------------------------------------')
const readFileSyncStart = new Date()
// https://nodejs.org/api/fs.html#fs_file_system_flags
const sourceBuffer = fs.readFileSync(sourceFile, { flag: 'rs+' } )
const readFileSyncStop = new Date()
console.log(`source file : ${sourceFile}`)
console.log(`readFileSync latency : ${readFileSyncStop - readFileSyncStart}ms`)
const toPCMStart = new Date()
const destinationBuffer = await toPCM( { sourceFile /*, sourceBuffer*/ } )
const toPCMStop = new Date()
const latencyMsecs = toPCMStop - toPCMStart
const bufferLenght = byteLength(destinationBuffer)
const durationSecs = duration(destinationBuffer)
const durationMsecs = durationSecs*1000
const realtimeFactor = rtf(latencyMsecs, durationMsecs)
console.log(`toPCM latency : ${latencyMsecs}ms`)
console.log(`audio PCM buffer length : ${aproxKiloBytes(bufferLenght)}`)
console.log(`audio duration : ${aproxSecs(durationSecs)}`)
console.log(`audio real time factor (RTF) : ${realtimeFactor}`)
}
if (require.main === module)
main()
module.exports = {
duration,
aproxSecs,
aproxKiloBytes,
byteLength,
rtf,
toPCM
}