LoginSignup
3
1

More than 3 years have passed since last update.

【Azure Cognitive Services】C#で作る「オウム返しナナミ」

Last updated at Posted at 2021-05-01

はじめに

しゃべった言葉をオウム返ししてくるぬいぐるみのことは知っていますか?遊んだことありますか?

イメージ.png

「僕の名前は太郎!」としゃべったら、ぬいぐるみも「僕の名前は太郎!」と同じ言葉を言い返してきます。ぬいぐるみの電池が切れるまで、ずっとオウム返ししてくるわけです。

以前、このような仕組みをAzure Cognitive Servicesを使ってJava(以下の記事参照)で作ってみましたが、今回はC#で作っていきます。この記事では、Azure portal上でCognitive Servicesのリソース作成済みであることを前提として進めていきますが、詳しい手順が知りたい場合はぜひ、下記の記事をご参照ください。

前提・環境

  • Windows 10 home
  • visual studio 2019
  • Azure portal上でCognitive Servicesのリソース作成済み
    • キーを取得できる。
    • 場所を取得できる。
  • NuGetパッケージ
    • Microsoft.CognitiveServices.Speech v1.16.0

全体のソースコード

using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

namespace AzureCognitiveServicesAPI
{
    class Program
    {
        static string subscriptionKey = "YourSubscriptionKey";
        static string serviceRegion = "YourServiceRegion";

        static string speechRecognitionLanguage = "ja-JP";
        static string speechName = "ja-JP-NanamiNeural";

        static async Task Main(string[] args)
        {
            var speechConfig = SpeechConfig.FromSubscription(subscriptionKey, serviceRegion);
            speechConfig.SpeechRecognitionLanguage = speechRecognitionLanguage;

            var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
            var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
            var synthesizer = new SpeechSynthesizer(speechConfig);

            var speakText = "";

            while (speakText != "終了。")
            {
                speakText = await SpeechToText(recognizer);
                await TextToSpeech(synthesizer, speakText);
            }

            await TextToSpeech(synthesizer, "プログラムを終了させますね。");
        }

        static async Task<string> SpeechToText(SpeechRecognizer recognizer)
        {
            var result = await recognizer.RecognizeOnceAsync();
            Console.WriteLine($"話した内容: {result.Text}");
            return result.Text;
        }

        static async Task TextToSpeech(SpeechSynthesizer synthesizer, string speakText)
        {
            await synthesizer.SpeakSsmlAsync(CreateTextReadOut(speakText));
        }

        static string CreateTextReadOut(string text)
        {
            return $"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='{speechRecognitionLanguage}'><voice name='{speechName}'>{text}</voice></speak>";
        }
    }
}

フィールド変数のsubscriptionKeyとserviceRegionに前提で取得しておいたキーと場所に書き換えてください。
実行すると、話した内容がコンソール上に出力され、さらにNanamiがその内容を話してくれるかと思います。

「終了」と話すとNanamiから「プログラムを終了させますね。」と言われ、プログラムが終了になります。

以上になります。ありがとうございました。

3
1
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
3
1