c#:语音播报(文本转语音)

环境:

  • window10
  • vs2019 16.5.5
  • .netframework4.5

一、关于语音播报

语音播报的功能属于操作系统自带的。win7和win10都自带,部分win7阉割版系统没有这项功能会导致运行报错:

检索 COM 类工厂中 CLSID 为 {D9F6EE60-58C9-458B-88E1-2F908FD7F87C} 的组件失
败,原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_
E_CLASSNOTREG))。

查看自己电脑是否支持语音播报功能,可以参考如下:
在这里插入图片描述

二、c#代码

直接新建个控制台程序,添加System.Speech.dll引用:
在这里插入图片描述
代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer speech = new SpeechSynthesizer();
            Console.Write("请输入文字:");
            string str = Console.ReadLine();
            try
            {
                if (string.IsNullOrEmpty(str))
                {
                    speech.Speak("请输入文字");
                }
                else
                {
                    speech.Speak(str);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"报错:{ex?.Message}");
            }
            Console.WriteLine("ok");
            Console.ReadLine();
        }
    }
}

运行后,带好耳机,查看效果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章