C#實現(xiàn)語音播報功能
本文實例為大家分享了C#實現(xiàn)語音播報功能的具體代碼,供大家參考,具體內容如下
環(huán)境:
window10
vs2019 16.5.5
.netframework4.5
一、關于語音播報
語音播報的功能屬于操作系統(tǒng)自帶的。win7和win10都自帶,部分win7閹割版系統(tǒng)沒有這項功能會導致運行報錯:
檢索 COM 類工廠中 CLSID 為 {D9F6EE60-58C9-458B-88E1-2F908FD7F87C} 的組件失敗,原因是出現(xiàn)以下錯誤: 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#實現(xiàn)將千分位字符串轉換成數(shù)字的方法
這篇文章主要介紹了C#實現(xiàn)將千分位字符串轉換成數(shù)字的方法,很適合初學者更好的理解C#字符串原理,需要的朋友可以參考下2014-08-08
WPF自定義TreeView控件樣式實現(xiàn)QQ聯(lián)系人列表效果
TreeView控件在項目中使用比較頻繁,下面這篇文章主要給大家介紹了關于WPF自定義TreeView控件樣式實現(xiàn)QQ聯(lián)系人列表效果的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2018-04-04

