【问题标题】:Stream audio with websocket and get back audio transcription obtained with Google speech API使用 websocket 流式传输音频并取回使用 Google 语音 API 获得的音频转录
【发布时间】:2019-08-25 02:28:18
【问题描述】:

我有一个客户端,它从麦克风获取音频,然后通过 websocket 流将其发送到远程服务器。

服务器端我从 websocket 获取音频流

const WebSocket = require('websocket-stream');
const wss = WebSocket.createServer({host: '192.168.254.161', port: 8090},handle);

function handle(stream)  {
  stream.pipe(recognizeStream); 
  stream.on('close', function (){
    console.log("stream closed")
  }).on('error', function() {
    console.log("stream error")
  })
}

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
        console.log('%s bytes received', message.length);
        ws.send("some mesage")
  }).on('close', function () {
       ws.send("End of audio data")
  }).on('error',function (err) {
      console.log("error:",err)
  });
});

并使用 SpeechClient 和 streamingRecognize 将其发送到 Google Speech API

const recognizeStream = client
  .streamingRecognize(request)
  .on('error', console.error)
  .on('data', (data) => {
    process.stdout.write(
      data.results[0] && data.results[0].alternatives[0]
        ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
        : `\n\nReached transcription time limit, press Ctrl+C\n`
    );
  });

一切正常,我将成绩单写入 che 服务器控制台..

现在我需要通过 websocket 将成绩单发回,但我找不到怎么做。我可以发回东西的唯一地方是 ws 事件处理程序,但在这里我无权访问脚本数据

【问题讨论】:

标签: websocket stream speech-to-text google-cloud-speech


【解决方案1】:

当连接可用时创建流并使用连接变量发回数据:

wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {
        console.log('%s bytes received', message.length);
        ws.send("some mesage")
  }).on('close', function () {
       ws.send("End of audio data")
  }).on('error',function (err) {
      console.log("error:",err)
  });


  const recognizeStream = client
        .streamingRecognize(request)
        .on('error', console.error)
        .on('data', (data) => {

          // We send it back here, ws is still accessible

          ws.send(
                data.results[0] && data.results[0].alternatives[0]
              ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
              : `\n\nReached transcription time limit, press Ctrl+C\n`
          );
        });

});

也有不同的方法 - 您可以使用全局变量来传递连接或将其包装在某个原型中。

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2013-04-12
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多