由于最近的工作需要用到文本转语音的功能,在网上找到的资料有些不完整,特此记录下整个完整功能。
这种方式的优点在于不会被浏览器限制,在js的文本转语音功能中,谷歌高版本的浏览器会阻止通过模拟点击的自动播放,而ie不会阻止.
操作系统:win10或win7(我自己用的是win10 据说有些阉割版的win7会报错)
IDE:VS2012 (可高于此版本)
.NET framework 4.0(可高于此版本)
1.C:\Windows文件夹下有Speech
2.控制面板有语音识别

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);
? ? ? ? }
? ? }
?
?
?
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持源码搜藏网。
热门源码