C#实现语音播报功能

2022-07-16,,

本文实例为大家分享了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();
        }
    }
}

运行后,带好耳机,查看效果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《C#实现语音播报功能.doc》

下载本文的Word格式文档,以方便收藏与打印。