使用 Watson Speech to Text 服务如何提取从 createRecognizeStream() 方法返回的值?
这是示例代码的一部分。我试图在终端中查看临时结果,但我得到的只是这个。如何设置显示结果的选项?
{ results: [ { alternatives: [Object], final: false } ],
result_index: 0 }
{ results: [ { alternatives: [Object], final: false } ],
result_index: 0 }
{ results: [ { alternatives: [Object], final: false } ]...
它们应该看起来像这样:
{
"results": [
{
"alternatives": [
{
"timestamps": [
[
"Here",
0.08,
0.63
],
[
"I",
0.66,
0.95
],
[
"Open",
0.95,
1.07
],
[
"a",
1.07,
1.33
],
[
"strong",
1.33,
1.95
],
[
"group",
2.03,
2.18
],
[
"of",
2.18,
2.72
],
[
示例代码:
// create the stream
var recognizeStream = speech_to_text.createRecognizeStream(params);
// pipe in some audio
fs.createReadStream(filepath).pipe(recognizeStream);;
// and pipe out the transcription
recognizeStream.pipe(fs.createWriteStream('transcriptions/transcription-' + path.basename(filepath) + '.txt'));
// listen for 'data' events for just the final text
// listen for 'results' events to get the raw JSON with interim results, timings, etc.
recognizeStream.setEncoding('utf8');// to get strings instead of Buffers from `data` events
['data','results', 'error', 'connection-close'].forEach(function(eventName) {
//JSON.stringify(eventName, null, 2)
//fs.writeFile('./transcript.txt', JSON.stringify(transcript), function(err) {if(err){return console.log('err')}});
recognizeStream.on('results', console.log.bind(console, ''));
});
如果您想要漂亮的多行 JSON,则需要对 JSON 进行字符串化:
您应该使用:而不是使用console.log
:
JSON.stringify(value[, replacer[, space]])
根据您的示例,您将执行以下操作:
var recognizeStream = speech_to_text.createRecognizeStream(params);
fs.createReadStream(filepath).pipe(recognizeStream);
recognizeStream.setEncoding('utf8');
// print interim results and final results
['data','results'].forEach(function(eventName) {
recognizeStream.on(eventName, JSON.stringify.bind(JSON));
});
// print error and connection-close events
['error', 'connection-close'].forEach(function(eventName) {
recognizeStream.on(eventName, console.log.bind(console, ''));
});
我是一名优秀的程序员,十分优秀!