我正在將語音轉成文字的結果回傳到index.js
然而在speechapisample.js裡面原本要callbackfunction(asrResult)的這行,卻說沒有這個function
如果我改成
if(callbackfunction) callbackfunction(asrResult);
則不會回傳結果。有查到要定義callbackfunction才能使用,卻不知道該從何定義起…
想請問各位高手大致上要如何處理?謝謝。
以下是目前的程式碼:
index.js
ffmpeg.on('close', (code) => {
console.log("開始進行語音辨識..." + sender_psid + '.wav');
speechApi.sendAudioFile( // <--開始
'asr',
'nli',
true,
'/tmp/' + sender_psid + '.wav',
0, function (sttText) {
console.log('辨識結果為:' + sttText);
var sendMessage = '辨識結果為:' + sttText;
response = {
"text": `${sendMessage}`
}
callSendAPI(sender_psid, response);
// sendTextMessage(sender_psid, '辨識結果為:'+ sttText);
handleMessage(sender_psid, response);
}
);
});
SpeechApiSample.js
SpeechApiSample.prototype.getRecognitionResult = function (apiName, seqValue, callbackFunction) {
// var callbackFunction = '';
var _this = this;
var url = this.getBaseQueryUrl(apiName, seqValue);
url += '&stop=1';
// Request speech recognition service by HTTP GET
request.get({
url: url,
headers: {
'Cookie': this.cookies
}
}, function(err, res, body) {
if (err) {
console.log(err);
}
}).on('response', function(response) {
var bufferhelper = new BufferHelper();
response.on('data', function(chunk) {
bufferhelper.concat(chunk);
});
response.on('end', function() {
var body = iconv.decode(bufferhelper.toBuffer(), 'UTF-8');
var result = JSON.parse(body);
var return_status = result['data']['asr']['final'];
// Try to get recognition result if uploaded successfully.
// We just check the state by a lazy way :P , you should do it by JSON.
if (return_status !== true) {
console.log("\n----- Get Recognition Result -----\n");
// Well, check by lazy way...again :P , do it by JSON please.
delayed.delay(function () {
_this.getRecognitionResult('asr', 'nli,seg', function(asrResult) {
callbackFunction(asrResult);
});
}, 500);
} else {
console.log("\n----- Get Recognition Result -----\n");
console.log("Result:\n\n" + body);
// 語音辨識後的結果
var json = JSON.parse(body);
var asrResult = json['data']['asr']['result'];
console.log("ASR Result = "+ asrResult);
// if(callbackFunction) callbackFunction(asrResult);
callbackFunction(asrResult);
}
});
});
}
error結果:
/app/SpeechApiSample.js:152
callbackFunction(asrResult);
^
TypeError: callbackFunction is not a function
at IncomingMessage.<anonymous> (/app/SpeechApiSample.js:152:5)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
最後我比對了您提供的github程式碼,發現了前面function有新增幾行callbackfunction,補上後就解決問題了,謝謝!
呃
重點應該是呼叫的時候有帶入
對的,因為我是看
https://tw.olami.ai/blog/article/40
一開始沒有仔細明白,但順著呼叫的function步驟走後,發現中間的function沒有帶入,再對照著看後就發現問題了~