In the era of artificial intelligence, text to speech is a popular function in artificial intelligence nowadays. All major companies have services in this area. They can convert various words to speech through interfaces, and even simulate real people. It is very powerful. Microsoft, the owner of. NET, actually also has services in this regard. If you don't have high requirements for language to text, you can use Microsoft's own speech conversion class library, and the implementation is very simple, only 5 lines of code to implement it. This article will introduce how to use it.
using step
- Environmental preparation
新建一个控制台项目,并使用 nuget 工具安装:System.Speech,也可以在本地类库添加安装,如下图 nuget 安装

2、输入如下代码,并添加引用using System.Speech.Synthesis;
static void Main(string[] args)
{
// 实例化 SpeechSynthesizer.
SpeechSynthesizer synth = new SpeechSynthesizer();
// 配置音频输出.
synth.SetOutputToDefaultAudioDevice();
// 字符串转语言.
synth.Speak("你好!DotNeT开发跳槽");
Console.WriteLine();
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
Successfully read "Hello! DotNeT Development Job Jump ", here is the console application, you can use winrom and wpf to implement it more perfectly.
extension instances
我们这里拿.NET网站实现一下转语音的功能,需求是输入文本框一句话,用这个System.Speech控件转换成音频,并加载到页面读取。
1、首先新建一个.NET的 web 应用,按上面的例子用nuget引入System.Speech
2、新建一个index.shtml页面,设计一个简单的文本框和查询按钮和一个音频输出控件,代码如下
<form>
<p>
Title: <input type="text" asp-for="Speektext" />
<input type="submit" value="生成语音" />
</p>
</form>
<audio style="width:350px;height:50px;" id="bofang" controls>
<source src="@Model.filename" type="audio/mpeg" />
</audio>
3、在Index.cshtml.cs页面新建一个输入文字转换文本属性和文件路径属性,并构造函数注入读取路径中间件。
private readonly IHostingEnvironment _IhostingEnvironment;
[BindProperty(SupportsGet = true)]
//用来输入要转换的文本
public string? Speektext { get; set; }
//用来输出文件路径
public string filename { get; set; }
//注入用来读取存放资源文件的路径
public IndexModel(IHostingEnvironment hostingEnvironment)
{
_IhostingEnvironment= hostingEnvironment;
}
4、在OnGetAsync方法中编写音频处理逻辑,代码如下:
public async Task OnGetAsync()
{
string wavname = "test";
string filePath = _IhostingEnvironment.WebRootPath+ $"\\speech\\{wavname}.wav";
bool isFile = System.IO.File.Exists(filePath);
if (isFile)
{
// 删除文件
System.IO.File.Delete(filePath);
}
if (string.IsNullOrEmpty(Speektext))
Speektext = "你好!欢迎关注“dotnet开发跳槽!”";
if (!string.IsNullOrEmpty(Speektext))
{
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
//配置音频文件,设置输出流和文件格式
synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
// 创建空的 Prompt 对象,并为添加内容、选择语音、控件语音属性和控件朗读单词的发音提供方法
PromptBuilder builder = new PromptBuilder();
builder.AppendText(Speektext);
//输出文件
synth.Speak(builder);
}
//返回文件路径
filename = $"\\speech\\{wavname}.wav";
}
}
- Use js to load it into the audio control on the front end.
<input type="button" id="aa" value="播放" onclick="bofang()" />
<script type="text/javascript">
function bofang() {
var url = "@Model.filename.Replace("\\","\\\\")";
var audio = document.getElementById('bofang');
$('#bofang').attr('src',url);
audio.play();
}
</script>
In this way, you can use the text box to enter content and then read the audio. You can encapsulate it with this code and transform it into a news audio reading. The effects are as follows:

Example code link:
https://pan.baidu.com/s/1IJadMleVEM3ePHE_KHqRqA?pwd=soiq
提取码:soiq
conclusion
This article introduces the simple method of using text to speech in. NET. You can refer to it and encapsulate it into your own method. Note that this example only supports the Windows environment. You can explore it yourself in cross-platform projects. I hope this article will have certain reference value for everyone's study and work. Thank you for your support.
This article refers to: Microsoft official technical documentation
webmaster extension
参考原文 .NET 3 行代码实现文字转语音功能,站长创建 MAUI Blazor 项目,按照文中步骤,添加 nuget 包,成功实现文字转语音功能,贴下关键代码并附上拍摄的视频:
@page "/"
@using System.Speech.Synthesis
<h1>请输入需要转换的文字,然后点击播放按钮</h1>
<MRow>
<MCol Cols="12" Md="4">
<MTextField @bind-Value="_message" Label="待转换文字"></MTextField>
</MCol>
</MRow>
<MRow>
<MCol Cols="12" Md="4">
<MButton Class="mr-4" Color="@(string.IsNullOrEmpty(_message) ? "warning" : "success")" OnClick="PlayWord">播放</MButton>
</MCol>
</MRow>
@code{
private string _message;
private SpeechSynthesizer _synth;
private void PlayWord()
{
if (_synth == null)
{
_synth = new SpeechSynthesizer();
_synth.SetOutputToDefaultAudioDevice();
}
_synth.Speak(_message);
}
}