65.9K
CodeProject 正在变化。 阅读更多。
Home

微软 .NET 语音合成的非常简单的介绍 (VB, C#, C++)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.23/5 (35投票s)

2008年8月21日

CPOL

1分钟阅读

viewsIcon

247882

downloadIcon

15605

一个示例应用程序,包含三种 .NET 语言(Basic、C#、C++)的源代码,演示如何使用新的 (.NET 3.0+) System.Speech 类。

引言

这段代码是关于如何在 .NET Framework v3.0 和 v3.5 中使用新的 System.Speech 类的一个介绍。 示例源代码包括一个应用程序,并且源代码以所有三种 .NET 语言(VB、C++、C#)提供。 它是一个简单的 Windows 应用程序,展示了如何使用文本转语音以及如何将语音导出到 WAV 文件。 源代码是在 Visual Studio 2008 中使用 .NET 3.5 编写的。

代码

命名空间

首先,我们需要从应用程序中引用 System.Speech 程序集。 从“项目”菜单中,选择“添加引用”。 然后从“.NET”选项卡中,突出显示 System.Speech 并选择“确定”。

然后将一个简单的命名空间导入到您的类文件(窗体文件)中。

// C#
using System.Speech.Synthesis;
// C++
using namespace System::Speech::Synthesis;
' VB
Imports System.Speech.Synthesis 

声明

接下来,我们需要声明并实例化一个 speech 对象。 该类是 System.Speech.Synthesis.Speechsynthesizer。 这个类拥有足够的属性和方法,可以使用操作系统的默认语言和语音来朗读一个 string 。 在 Microsoft Windows Vista 中,默认语音是 Microsoft Ana。 对于 Windows XP,它是 Microsoft Sam。 您可以安装其他语音,但那将留到另一篇文章中。

// C#
SpeechSynthesizer speaker = new SpeechSynthesizer();
// C++
public: SpeechSynthesizer speaker;
' VB
Dim speaker as New SpeechSynthesizer()

用法

最后,我们调用对象的 Speak SpeakAsync 方法,传入包含我们要朗读的文本的 string

// C#
speaker.Rate = 1;
speaker.Volume = 100;
speaker.Speak("Hello world.");
// C++
speaker.Rate = 1;
speaker.Volume = 100;
speaker.Speak("Hello world.");
' VB
speaker.Rate = 1
speaker.Volume = 100
speaker.Speak("Hello world".)

您可以看到从图像中,我也包含了语音速率和音量的设置。 示例程序还包含将朗读的 string 保存到 WAV 文件的代码。 然后您可以将系统的声音设置为您创建的 WAV 文件,您的计算机就会听起来像 Dr. Falkan 一样。 你想玩个游戏吗?

// CS
speaker.SetOutputToWaveFile("c:\soundfile.wav");
speaker.Speak("Hellow world.");
speaker.SetOutputToDefaultAudioDevice();
//Must remember to reset out device or the next call to speak 
//will try to write to a file
// C++
speaker.SetOutputToWaveFile("c:\soundfile.wav");
speaker.Speak("Hellow world.");
speaker.SetOutputToDefaultAudioDevice();
//Must remember to reset out device or the next call to speak 
//will try to write to a file
' VB
speaker.SetOutputToWaveFile("c:\soundfile.wav")
speaker.Speak("Hellow world.")
speaker.SetOutputToDefaultAudioDevice()
'Must remember to reset out device or the next call to speak 
'will try to write to a file

历史

  • 2008 年 8 月 21 日:初始发布
© . All rights reserved.