ロボットと共に

Life with Robot

C#とGoogleAPIで音声認識を簡単に

前回はUbuntuにROSを導入し、rospeexを試してみました。

今回は、C#とGoogleAPIを使って音声認識音声合成を試してみたいと思います。

 

GoogleApiKitとは

GoogleApiKitは、以下の4つの機能が使えるDLL集です。

  1. 検索 GoogleSearch.dll
  2. 音声認識 SpeechDialog.dll
  3. 予測変換 GoogleSuggest.dll
  4. 音声合成 GoogleTTS.dll

導入

導入は至って簡単です。DLLなので実行ファイルと同じディレクトリにそのまま置きます。今回は音声認識音声合成をするので、音声認識[SpeechDialog.dll][flac.exe]と音声合成[GoogleTTS.dll][cmdmp3.exe]の4つを置きます。サンプルコードで、C# FormがありますのでC#コンソールやWPFにも導入し易いです。コンソールとWPFで試して見ましたが、導入は簡単でした。コンソールのサンプルを

 

サンプルソースコード

 

using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        //dllのImport
        //SpeechAPI
        [DllImport("SpeechDialog.dll")]
        public extern static bool SpeechDlg(IntPtr Handle, [MarshalAs(UnmanagedType.LPArray)] byte[] res);
        //音声合成API
        [DllImport("GoogleTTS.dll")]
        public extern static void TTS(string in_str);

        static void Main(string[] args)
        {
            for (int i = 0; i < 2; i++)
            {
                string test = string.Empty;
                byte[] res_byte = new byte[4096];
                bool res;
                res = SpeechDlg(IntPtr.Zero, res_byte);
                //変換(SJISだと"shift_jis")
                string str = System.Text.Encoding.GetEncoding("shift_jis").GetString(res_byte);
                if (res)
                {
                    test = str;
                }

                if (test != "")
                {
                    // 音声認識
                    if (test.Contains("今何時"))
                    {
                        string text = "今、" + DateTime.Now.Hour.ToString() + "時" + DateTime.Now.Minute.ToString() + "分です。";
                        TTS(text);
                    }
                    else
                    {

                        TTS(test);
                    }

                }
            }
        }
    }
}

 

実行手順

  1. 実行ファイル下に、[SpeechDialog.dll][flac.exe][GoogleTTS.dll][cmdmp3.exe]の4つを置く。
  2. ソースコードを実行する。
  3. For文で2回まわるようにしているので、マイクに「今何時」と話すと「今、○時□分です。」と答えてくれます。違う言葉の場合、その言葉を『言霊』します。所謂、オウム返しです♪

f:id:Mikan6:20141208212050j:plain

                  実行画面

最後に

 サンプルソースコードは、あくまでも参考としてご利用下さい。また、GoogleApiKitのライセンスにも目を通して、ご利用下さい。