日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#實現文本轉語音功能_C#教程

作者:qq_32915337 ? 更新時間: 2022-05-29 編程語言

由于最近的工作需要用到文本轉語音的功能,在網上找到的資料有些不完整,特此記錄下整個完整功能。

這種方式的優點在于不會被瀏覽器限制,在js的文本轉語音功能中,谷歌高版本的瀏覽器會阻止通過模擬點擊的自動播放,而ie不會阻止.

一.確認研發環境

操作系統:win10或win7(我自己用的是win10 據說有些閹割版的win7會報錯)

IDE:VS2012 (可高于此版本)

.NET framework 4.0(可高于此版本)

二.系統自帶語音識別功能

1.C:\Windows文件夾下有Speech

2.控制面板有語音識別

三.DLL引用

1.選中要使用該功能的程序右鍵選擇"添加引用"

2.選中"程序集"--"框架"下的System.Speech

四.代碼

需要注意的是:

1.頁面需要設置為異步

2.通過委托代理的方式調用,防止頁面無響應

3.頁面代碼如下:

aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="yy.aspx.cs" Inherits="yy" Async="true" %>
?
<!DOCTYPE html>
?
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
? ? <title>文字轉語音測試</title>
</head>
<body>
? ? <form id="form1" runat="server">
? ? <div>
? ? <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
? ? </div>
? ? ? ??
? ? </form>
</body>
</html>

aspx.cs:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Speech.Synthesis;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
?
public partial class yy : System.Web.UI.Page
{
? ? protected void Page_Load(object sender, EventArgs e)
? ? {
?
? ? }
? ? /// <summary>
? ? /// 文字轉語音
? ? /// </summary>
? ? /// <param name="content">語音內容</param>
? ? delegate void MyDelegate(string content);
? ? string content = "有新的訂單,請及時處理";
? ? SpeechSynthesizer synthesizer = new SpeechSynthesizer(); //點擊開始按鈕?
?
? ? //開始朗讀
? ? private void speakParagh(string text)
? ? {
? ? ? ? synthesizer.Speak(text);
? ? }
?
? ? //朗讀結束后釋放資源?
? ? private void Completed(IAsyncResult result)
? ? {
? ? ? ? synthesizer.SpeakAsyncCancelAll();
? ? }
?
? ? protected void Button1_Click(object sender, EventArgs e)
? ? {
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? MyDelegate myDelegate = new MyDelegate(speakParagh); //異步調用委托?
? ? ? ? ? ? myDelegate.BeginInvoke(content, new AsyncCallback(Completed), null); //在啟動異步線程后,主線程可以繼續工作而不需要等待
? ? ? ? }
? ? ? ? catch (Exception ex)
? ? ? ? {
? ? ? ? ? ? Console.WriteLine("報錯:" + ex.Message);
? ? ? ? }
? ? }
?
?
?
}

原文鏈接:https://blog.csdn.net/qq_32915337/article/details/123404503

相關推薦

欄目分類
最近更新