2020-08-25 17:49:29 +03:00
const DeepSpeech = require ( 'deepspeech' ) ;
2019-12-04 18:38:56 +03:00
const Fs = require ( 'fs' ) ;
const Sox = require ( 'sox-stream' ) ;
const MemoryStream = require ( 'memory-stream' ) ;
const Duplex = require ( 'stream' ) . Duplex ;
const Wav = require ( 'node-wav' ) ;
2021-01-06 20:48:06 +03:00
let modelPath = './models/deepspeech-0.9.3-models.pbmm' ;
2019-12-04 18:38:56 +03:00
2020-08-25 17:49:29 +03:00
let model = new DeepSpeech . Model ( modelPath ) ;
2019-12-04 18:38:56 +03:00
let desiredSampleRate = model . sampleRate ( ) ;
2021-01-06 20:48:06 +03:00
let scorerPath = './models/deepspeech-0.9.3-models.scorer' ;
2019-12-04 18:38:56 +03:00
2020-01-20 18:20:22 +03:00
model . enableExternalScorer ( scorerPath ) ;
2019-12-04 18:38:56 +03:00
let audioFile = process . argv [ 2 ] || './audio/2830-3980-0043.wav' ;
if ( ! Fs . existsSync ( audioFile ) ) {
console . log ( 'file missing:' , audioFile ) ;
process . exit ( ) ;
}
const buffer = Fs . readFileSync ( audioFile ) ;
const result = Wav . decode ( buffer ) ;
if ( result . sampleRate < desiredSampleRate ) {
console . error ( 'Warning: original sample rate (' + result . sampleRate + ') is lower than ' + desiredSampleRate + 'Hz. Up-sampling might produce erratic speech recognition.' ) ;
}
function bufferToStream ( buffer ) {
let stream = new Duplex ( ) ;
stream . push ( buffer ) ;
stream . push ( null ) ;
return stream ;
}
let audioStream = new MemoryStream ( ) ;
bufferToStream ( buffer ) .
pipe ( Sox ( {
global : {
'no-dither' : true ,
} ,
output : {
bits : 16 ,
rate : desiredSampleRate ,
channels : 1 ,
encoding : 'signed-integer' ,
endian : 'little' ,
compression : 0.0 ,
type : 'raw'
}
} ) ) .
pipe ( audioStream ) ;
audioStream . on ( 'finish' , ( ) => {
let audioBuffer = audioStream . toBuffer ( ) ;
const audioLength = ( audioBuffer . length / 2 ) * ( 1 / desiredSampleRate ) ;
console . log ( 'audio length' , audioLength ) ;
2020-01-27 20:24:05 +03:00
let result = model . stt ( audioBuffer ) ;
2019-12-04 18:38:56 +03:00
console . log ( 'result:' , result ) ;
} ) ;