Синтез речи с помощью c #, заставьте ваше приложение говорить

Следующий код показывает, как использовать синтез речи в C #.

В классе есть глобальная переменная sintetizador, помните, что нам нужно включить System.Speech.Synthesis.

В этом примере используется метод Async, и вы узнаете, как выполнить речь со слушателями (начало, конец) без блокировки пользовательского интерфейса. Прочитайте краткое описание каждой функции для более подробного объяснения.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Synthesizer.net
{
class SynthesizerUIHelper
{
private SpeechSynthesizer sintetizador = new SpeechSynthesizer();
///
/// Speak a string of text asynchronously (without lock the ui). But we will add support for the events that it triggers.
///
///
public void speak(string content = "")
{
try
{
sintetizador.SelectVoice("Microsoft Irina Desktop"); // First list all the voices of the pc with
sintetizador.SpeakProgress += new EventHandler(synthesizer_SpeakProgress);
sintetizador.SpeakCompleted += new EventHandler(synthesizer_SpeakCompleted);
sintetizador.SetOutputToDefaultAudioDevice();
sintetizador.SpeakAsync(content);
}
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
}
private void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
Console.WriteLine("SpeakProgress: AudioPosition=" + e.AudioPosition + ",\tCharacterPosition=" + e.CharacterPosition + ",\tCharacterCount=" + e.CharacterCount + ",\tText=" + e.Text);
}
private void synthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e)
{
Console.WriteLine("SpeakProgress: AudioPosition=" + e.AudioPosition + ",\tCharacterPosition=" + e.CharacterPosition + ",\tCharacterCount=" + e.CharacterCount + ",\tText=" + e.Text);
}
///
/// Stop the previous async speech
///
public void stop()
{
try
{
sintetizador.SpeakAsyncCancelAll();
}
catch (ObjectDisposedException) { }
}
///
/// Set the sinthesizer volume with an integer (0 - 100)
///
///
public void setVolume(int level)
{
if (level > 100)
{
sintetizador.Volume = 100;
}
else if (level < 0)
{
sintetizador.Volume = 0;
}
else
{
sintetizador.Volume = level;
}
}
public void resume()
{
sintetizador.Resume();
}
public void pause()
{
sintetizador.Pause();
}
///
/// Send speechSynthesizer output to a .wav file
///
///
public void toWAVFile(string content = "")
{
sintetizador.SelectVoice("Microsoft Irina Desktop");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
sintetizador.SetOutputToWaveFile(path + "/mySpokenAudio.wav");
sintetizador.Speak(content);
MessageBox.Show("File exported succesfully !",".wav File succesfully exported",MessageBoxButtons.OK,MessageBoxIcon.Information);
sintetizador.SetOutputToDefaultAudioDevice();
}
///
/// Shows a list of all the voices available in the pc, note that you need to figure out a method to choose the voice in the previous functions.
///
public void listAvailableVoicesConfigurator()
{
using (sintetizador)
{
foreach (InstalledVoice voice in sintetizador.GetInstalledVoices())
{
var info = voice.VoiceInfo;
Console.WriteLine(info.name + " - " +info.Culture);
}
}
}
}
}

Этот проект github представляет собой простое приложение, созданное с использованием cefsharp и .NET Framework 4.5., простой пользовательский интерфейс, который позволяет вам выбрать предустановленный голос из окон, говорить, приостанавливать и отображать ход речи в индикаторе выполнения, это хорошее начало, чтобы понять, как работает синтез речи.

Ссылка на основную публикацию
Adblock
detector