首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >能在node js中将电话从本地语言翻译成英语吗?

能在node js中将电话从本地语言翻译成英语吗?
EN

Stack Overflow用户
提问于 2021-09-03 12:25:30
回答 1查看 55关注 0票数 1

我已经尝试了很长一段时间,试图实现Google Media translate来翻译node js中的电话呼叫,但它给了我错误,我真的不知道如何修复它们。

下面是我的代码:

代码语言:javascript
运行
复制
const WebSocket = require("ws");
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const wss = new WebSocket.Server({ server });
const path = require("path");

let stream = null;
wss.on("connection", function connection(ws) {
    //Call Initiated
      console.log("New Connection Initiated");
      ws.on("message", function incoming(message) {
        const msg = JSON.parse(message);
        switch (msg.event) {
          case "connected":
            //Call connected
            console.log(`A new call has connected.`);

            const audio = require('@google-cloud/media-translation');
            const encoding = 'linear16';
            const sourceLanguage = 'sw';
            const targetLanguage = 'en-US';
            const sampleRateHertz = 8000;
            const model = 'google-provided-model/phone-call'
            const client = new audio.SpeechTranslationServiceClient;  
      
            const config = {
              audioConfig: {
                audioEncoding: encoding,
                sourceLanguageCode: sourceLanguage,
                sampleRateHertz : sampleRateHertz,
                targetLanguageCode: targetLanguage,
                targetModel : model
              },
              singleUtterance: false,
            };
            const initialRequest = {
              streamingConfig: config,
              audioContent: null,
            };
            let currentTranslation = '';
            let currentRecognition = '';
      
            stream = client
            .streamingTranslateSpeech()
            .on("error", console.error)
            .on('data', response => {
              const {result, speechEventType} = response;
              if (speechEventType === 'END_OF_SINGLE_UTTERANCE') {
                console.log(`\nFinal translation: ${currentTranslation}`);
                console.log(`Final recognition result: ${currentRecognition}`);
                stream.destroy();
              } else {
                currentTranslation = result.textTranslationResult.translation;
                currentRecognition = result.recognitionResult;
                console.log(`\nPartial translation: ${currentTranslation}`);
                console.log(`Partial recognition result: ${currentRecognition}`);
              }
              // Send data to Google Media Translator
              let isFirst = true;
              msg.stream()
              .on('data', chunk => {
                if (isFirst) {
                  stream.write(initialRequest);
                  isFirst = false;
                }
                const request = {
                  streamingConfig: config,
                  audioContent: chunk.toString('base64'),
                };
                if (!stream.destroyed) {
                  stream.write(request);
                }
              })
              .on('close', () => {
                console.log("Stream Closed...")
              });
            });
             //Create Stream to the Google Speech to Text API
            break;
          case "start":
            console.log(`Starting Media Stream ${msg.streamSid}`);
            break;
          case "media":
            // Write Media Packets to the recognize stream
            stream.write(msg.media.payload);
            break;
          case "stop":
            console.log(`Call Has Ended`);
            break;
        }
      });  
    });
server.listen(8080);
console.log('Listening at Port 8080');

现在,在我运行代码并调用twilio电话号码之后,这是它生成的错误

代码语言:javascript
运行
复制
Error: 3 INVALID_ARGUMENT: The first request must be a StreamingTranslateSpeechConfig request!
    at Object.callErrorFromStatus (/home/stanley/C-M-System/node_modules/@grpc/grpc-js/build/src/call.js:31:26)
    at Object.onReceiveStatus (/home/stanley/C-M-System/node_modules/@grpc/grpc-js/build/src/client.js:390:49)
    at Object.onReceiveStatus (/home/stanley/C-M-System/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:299:181)
    at /home/stanley/C-M-System/node_modules/@grpc/grpc-js/build/src/call-stream.js:145:78
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  code: 3,
  details: 'The first request must be a StreamingTranslateSpeechConfig request!',
  metadata: Metadata {
    internalRepr: Map { 'grpc-server-stats-bin' => [Array] },
    options: {}
  }
}

我是网络编程的新手,所以如果有人知道如何解决这个问题,那可以帮助我。在这一点上,我已经束手无策。

EN

回答 1

Stack Overflow用户

发布于 2021-09-08 10:06:14

我找到了这个sample,我发现了一些不同的东西,也许这就是问题所在。

尝试将您的const音频和const客户端替换为‘’//导入云媒体翻译客户端库const { SpeechTranslationServiceClient,}= require('@google- Cloud / Media - Translation ');

//创建客户端const client = new SpeechTranslationServiceClient();‘’

如果能用的话请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69044935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档