c# 文本转语音(语音播报)

由于最近的工作需要用到文本转语音的功能,在网上找到的资料有些不完整,特此记录下整个完整功能

这种方式的优点在于不会被浏览器限制,在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);
        }
    }



}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值