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();
        }
    }
}

運行後,帶好耳機,查看效果:
在這裏插入圖片描述

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