Text-To-Speech per .NET Micro Framework (Italiano)

Inviato da Marco Minerva

Sono sempre stato appassionato dalla possibilità di far parlare le mie applicazioni.  Ho così realizzato una libreria per .NET Micro Framework che sfrutta Microsoft Translator per ottenere uno stream contenente il parlato del testo che è stato inviato al servizio tramite una chiamata REST. Attualmente, sono supportate ben 44 lingue, tra cui Inglese, Italiano, Tedesco, Francese, Spagnolo, Giapponese e Cinese.

Per eseguire il codice, è necessario ottenere un Bing Application ID, che può essere richiesto gratuitamente visitando la pagina http://msdn.microsoft.com/en-us/library/ff512386.aspx. L’utilizzo della libreria è molto semplice:

SpeechSynthesizer speech = new SpeechSynthesizer(APP_ID);

string text = "Ti auguro una buona giornata!";
string language = "it";

bytes[] data = speech.GetSpeakBytes(text, language);

In questo modo otteniamo un array di byte che contiene lo stream con il parlato, che possiamo riprodurre utilizzando le funzionalità audio del nostro device, ad esempio tramite il Music Module di GHI Electronics.

Il metodo sopra descritto è bloccante, ma esiste anche la corrispondente versione asincrona, GetSpeakBytesAsync.

SpeechSynthesizer speech = new SpeechSynthesizer(APP_ID);
speech.GetSpeakBytesCompleted +=
                 new SpeechSynthesizer.GetSpeakBytesEventHandler(speech_GetSpeakBytesCompleted);

string text = "Ti auguro una buona giornata!";
string language = "it";

speech.GetSpeakBytesAsync(text, language);    // Questo metodo ritorna immediatamente

private void speech_GetSpeakBytesCompleted(object sender, GetSpeakBytesEventArgs e)
{
    if (e.Error == null)
        Debug.Print("Ottenuto un parlato di " + e.Data.Length + " byte");
    else
        Debug.Print("Si è verificato un errore: " + e.Error.Message);
}

La libreria è disponibile su MSDN Code Gallery. Per facilitarne la diffusione, inoltre, l’ho pubblicata anche su NuGet (è sufficiente una ricerca per TranslatorService.Speech).

TranslatorService.Speech

La libreria disponibile su NuGet

Concludo dicendo che esiste anche una versione della libreria per il .NET “Full” Framework. Su NuGet sono disponibili entrambe le versioni, quindi a seconda del tipo di progetto sarà referenziata la DLL corretta.

Il codice che esegue l’esempio del video è illustrato di seguito.

using Microsoft.SPOT;

using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using MicroTranslatorService.Speech;
namespace TextToSpeech
{
    public partial class Program
    {
        private const string APP_ID = "Add your Bing user ID";
        SpeechSynthesizer speech;
        byte[] bytes;
        uint index;
        void ProgramStarted()
        {
            button.ButtonPressed += new Button.ButtonEventHandler(button_ButtonPressed);
            music.MusicFinished += new MusicFinishedPlayingEventHandler(music_MusicFinished);
            index = 0;

            speech = new SpeechSynthesizer(APP_ID);
            speech.GetSpeakBytesCompleted += new SpeechSynthesizer.GetSpeakBytesEventHandler(speech_GetSpeakBytesCompleted);

            Debug.Print("Program Started");
        }

        void music_MusicFinished()
        {
            Debug.Print("Audio finished.");
        }

        void button1_ButtonPressed(Button sender, Button.ButtonState state)
        {
            if (bytes != null)
                music.Play(bytes);
        }

        void speech_GetSpeakBytesCompleted(object sender, GetSpeakBytesEventArgs e)
        {
            if (e.Error == null)
            {
                Debug.Print("Retrived a speech of " + e.Data.Length + " bytes length");
                bytes = e.Data;
                music.Play(bytes);
            }
            else
                Debug.Print("There was an error: " + e.Error.Message);
        }

        void SendRequest(string text, string language)
        {
            Debug.Print("Submitting request...");
            display.SimpleGraphics.Clear();
            display.SimpleGraphics.DisplayTextInRectangle(text, 20, 20, 300, 250, GT.Color.Cyan,
                Resources.GetFont(Resources.FontResources.NinaB),
                GTM.Module.DisplayModule.SimpleGraphicsInterface.TextAlign.Left,
                GTM.Module.DisplayModule.SimpleGraphicsInterface.WordWrap.Wrap,
                GTM.Module.DisplayModule.SimpleGraphicsInterface.Trimming.WordEllipsis,
                GTM.Module.DisplayModule.SimpleGraphicsInterface.ScaleText.None);

            speech.GetSpeakBytesAsync(text, language);
        }

        void button_ButtonPressed(Button sender, Button.ButtonState state)
        {
            switch (index)
            {
                case 0:
                    {
                        SendRequest("I am very interested in the possibility of making my applications speak. So, I have realized a library for .NET Micro Framework that uses Microsoft Translator to obtain streams of wave-file speaking text in the desired language. At this moment, there are 44 supported languages, including English, Italian, German, French, Spanish, Japanese and Chinese.", "en");
                        index++;
                        break;
                    }
                case 1:
                    {
                        SendRequest("Je suis très intéressé par la possibilité de rendre mes applications parler. Alors, j'ai réalisé une bibliothèque pour. NET Micro Framework qui utilise Microsoft Translator pour obtenir des flux de texte parlant fichier wave dans la langue désirée. En ce moment, il ya 44 langues prises en charge, y compris l'anglais, italien, allemand, français, espagnol, japonais et chinois.", "fr");
                        index++;
                        break;
                    }

                case 2:
                    {
                        SendRequest("Ich bin sehr in die Möglichkeit, meine Anwendungen sprechen interessiert. Also, ich habe eine Bibliothek für. NET Micro Framework, Microsoft Translator nutzt, um Ströme von wave-Datei sprechenden Text in die gewünschte Sprache zu erhalten realisiert. In diesem Moment gibt es 44 unterstützten Sprachen, darunter Englisch, Italienisch, Deutsch, Französisch, Spanisch, Japanisch und Chinesisch.", "de");
                        index++;
                        break;
                    }
                case 3:
                    {
                        SendRequest("Does this train go to Barcelona?", "es");
                        index++;
                        break;
                    }
                case 4:
                    {
                        SendRequest("Please pass the chocolate.", "pt");
                        index++;
                        break;
                    }
                case 5:
                    {
                        SendRequest("Thanks for all the fish.", "no");
                        index++;
                        break;
                    }
                case 6:
                    {
                        SendRequest("Will the winter never end?", "ru");
                        index++;
                        break;
                    }
                case 7:
                    {
                        //SendRequest("私は非常に私のアプリケーションは、話すことの可能性に興味を持っています。だから、私は希望の言語でウェーブファイルを話すのテキストのストリームを取得するには、Microsoft Translatorを使用している。NET Micro Frameworkのためのライブラリを実現しています。現時点では、英語、イタリア語、ドイツ語、フランス語、スペイン語、日本語、中国語など44言語がサポートさ、があります", "ja");
                        index++;
                        break;
                    }
                default:
                    {
                        index = 0;
                        break;
                    }
            }
        }
    }
}
Advertisement

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: