LoginSignup
25
18

More than 5 years have passed since last update.

Google Cloud Speech APIと、Google Cloud Translation APIと google-home-notifierでリアルタイム翻訳を作る

Last updated at Posted at 2018-01-27

Google Cloud Speech APIと、Google Cloud Translation APIと google-home-notifierを使ってリアルタイム翻訳を作ります。

IMAGE ALT TEXT HERE

Google Cloud にプロジェクトを作成してキーの発行などは事前に行い、認証可能な状態にしておいてください。
勿論、Google Cloud SDKなども用意しておいてください。
今回はNodejsで作成します。

入力

Google Speech APIにテキスト化してもらうために、マイクで入力できる環境を用意します。
私はMacで開発を行なっています。
node-record-lpcm16をインストールします。
https://www.npmjs.com/package/node-record-lpcm16

録音された音声をGoogle Speech APIに渡すと、テキストになって返ってきます。
今回、リアルタイムで行いたいので、ストリーミング音声認識を行います。
https://github.com/googleapis/nodejs-speech

音声を、Google Speech APIのrecognizeStreamに渡します。

翻訳

テキスト化された内容を、Google Translation APIに渡して翻訳します。
https://github.com/googleapis/nodejs-translate

出力

翻訳された内容をGoogle Homeに喋らせるために、google-home-notifierに内容を通知します。
https://github.com/noelportugal/google-home-notifier

プログラム

これらをまとめると、以下の通りになります。

stream.js
// 認証キー
const authKey = 'キーのパス名'
// 入力する言語 https://cloud.google.com/speech/docs/languages?hl=ja
var inputLanguageCode = 'ja-JP';
// 出力する言語 https://cloud.google.com/translate/docs/languages?hl=ja
var outputLanguageCode = process.argv[2];
if ( outputLanguageCode == null ) {
    console.log('ERROR: Translate language code is required.');
    process.exit();
}
var googleHomeIp = 'Google HomeのIPアドレス';

// Sox
const Record = require('node-record-lpcm16');

// Speech
const Speech = require('@google-cloud/speech');

// Translate
const Translate = require('@google-cloud/translate');

// GoogleHome Notifier
const GoogleHome = require('google-home-notifier');

// Creates a client
const SpeechClient = new Speech.SpeechClient({
  keyFilename: authKey
});
const TranslateClient = new Translate({
  keyFilename: authKey
});

// The encoding of the audio file, e.g. 'LINEAR16'
const encoding = 'LINEAR16';
// The sample rate of the audio file in hertz, e.g. 16000
const sampleRateHertz = 16000;

// Google Speech - Create a recognize stream
const recognizeStream = SpeechClient
    .streamingRecognize({
        config: {
            encoding: encoding,
            sampleRateHertz: sampleRateHertz,
            languageCode: inputLanguageCode
        },
        interimResults: false // If you want interim results, set this to true - 途中経過を出力する
    })
    .on('data', function(response) {

        let texts = [];
        texts.push(response.results[0].alternatives[0].transcript);

        // Translate
        TranslateClient
        .translate(texts[texts.length-1], outputLanguageCode)
        .then(results => {
            const translation = results[0];
            console.log('Text:'+texts[texts.length-1]);
            console.log('Translation:'+translation);

            // GoogleHome 
            GoogleHome.ip(googleHomeIp, outputLanguageCode);
            GoogleHome.notify(translation, function(res) {
              console.log(res);
            });

        })
        .catch(err => {
            console.error('ERROR:', err);
        });
});

// Start recording and send the microphone input to the Speech API
Record
.start({
    sampleRateHertz: sampleRateHertz,
    threshold: 0.5,
    silence: '1.0', // 終了させる無音間隔(sec)
    verbose: true,
    recordProgram: 'rec'
})
.pipe(recognizeStream)
.on('error', function() {
    console.log(error);
});

実行

以下で実行すると、Macが入力待ちになるので、適当に話しかけてください。
録音が終わると翻訳が終わった後、Google Homeに翻訳内容が送られて、話してくれるはずです。

node 実行するプログラムファイル名 翻訳する言語

エスペラント語もラテン語も、ロシア語もなんだって話せます。
女性を口説くために、10ヶ国語を話せるようになった知り合いがいました。
これで大丈夫です、頑張ってくださいね!

25
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
18