如何使用事件发射器模式从longrunningRecognize返回结果?

时间:2019-03-06 18:18:30

标签: javascript node.js google-speech-api

因此,我遵循了Google example的事件发射器模式,但略作更改以满足我的需要。但是有些东西丢失了,我的函数转录返回未定义。

请帮帮我,如何从operation.on('complete'...)返回结果?

这是通话记录功能的方式:

const { transcribe } = require('./helpers/')
const tr = await transcribe(gcsuri) 

这是转录的实现:

exports.transcribe = async (gcsuri) => {

    const reducerforSingleAlternative = (obj, item, index, array) => {
        item.alternatives[0].words.map(word => obj.words.push(word))
        obj.confidence += item.alternatives[0].confidence
        obj.transcript += item.alternatives[0].transcript
        if (index === (array.length - 1)) {
            obj.confidence = obj.confidence / array.length
        }
        return obj
    }

    process.env.GOOGLE_APPLICATION_CREDENTIALS = process.env.SPEECH_KEY
    const speech = require('@google-cloud/speech').v1p1beta1
    const client = new speech.SpeechClient()
    const audio = {
        uri: gcsuri
    }
    const request = {
        audio: audio,
        config: { encoding: 'OGG_OPUS',
                  sampleRateHertz: 24000,
                  languageCode: 'ru',
                  enableSpeakerDiarization: true,
                  enableWordConfidence: true,
                  maxAlternatives: 1,
                  enableAutomaticPunctuation: true, 
                  enableWordTimeOffsets: true, 
                }
    }

const [operation, initialApiResponse] = await client.longRunningRecognize(request)


        operation.on('progress', (metadata, apiResponse) => {
            console.log('metadata', metadata, apiResponse)
        })

        operation.on('complete', (result, metadata, finalApiResponse) => {
            console.log("complete!")
            const res = result.results.reduce(reducerforSingleAlternative, {words:[], confidence:0, transcript:""})
            return res
        })

        operation.on('error', err => {
            throw(err)
        })
}

我也尝试过

return await new Promise((resolve, reject) => {

    operation.on...
    ...
}

但是奇怪的是,这段代码对一个请求产生了两个相同的操作,所以我猜我做错了事

0 个答案:

没有答案