一、项目中一直用到了文字转语音的功能,需求也比较简单,就是将一段报警信息通过语音的方式播放出来,之前一直采用CS客户端,利用微软自带的Speech语音播放库就可以完成,

1.1 封装winSpedk类代码如下:

namespace Speak
{
using System;
using System.Runtime.CompilerServices;
using System.Speech.Synthesis;
using System.Threading;
using SpeechLib; public class WinSpeak
{
#region 属性
private SpeechSynthesizer Speak;
public event ErrorInfo ErrorInfoEvent;
private Thread thVoice;
private string strVoiceMsg;
SpVoice Voice = null;
private static WinSpeak _intence;
#endregion private WinSpeak()
{
Voice = new SpVoice();
} #region 方法
public static WinSpeak _Init()
{
if (_intence == null)
_intence = new WinSpeak(); return _intence;
}
/// <summary>
/// 读语音
/// </summary>
private void SpeakM()
{
try
{
if (Speak != null)
{
this.Speak.SpeakAsync(strVoiceMsg);
}
}
catch (Exception exception)
{
this.ErrInfo(exception);
}
}
/// <summary>
/// 异步播放文本语音
/// </summary>
/// <param name="msg"></param>
public void BeginSpeakText(string msg)
{
try
{
if (Speak != null)
{
Speak.SpeakAsyncCancelAll();
Speak.Dispose();
} if (thVoice != null && thVoice.ThreadState == ThreadState.Running)
{
thVoice.Abort();
} Speak = new SpeechSynthesizer();
Speak.SetOutputToDefaultAudioDevice(); strVoiceMsg = msg; //thVoice = new Thread(new ThreadStart(SpeakM));
//thVoice.Start();
Speak.SpeakAsync(msg); GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception exception)
{
this.ErrInfo(exception);
}
}
/// <summary>
/// 播放文本语音
/// </summary>
/// <param name="msg"></param>
public void SpeakText(string msg)
{
try
{
this.Speak = new SpeechSynthesizer();
this.Speak.Speak(msg);
this.Speak.SetOutputToNull();
this.Speak.Dispose();
}
catch (Exception exception)
{
this.ErrInfo(exception);
}
}
/// <summary>
/// Speech播放文本合成语音
/// </summary>
/// <param name="msg"></param>
public void Speech_SpeakText(string msg)
{
try
{
if (Voice != null)
{
Voice.Speak(null, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
Voice.Speak(msg, SpeechVoiceSpeakFlags.SVSFlagsAsync);
}
}
catch (Exception ex)
{
this.ErrInfo(ex);
}
}
/// <summary>
/// 关闭语音释放资源
/// </summary>
public void SpeakClose()
{
try
{
if (Speak != null)
{
this.Speak.SpeakAsyncCancelAll();
this.Speak.Dispose();
} if (Voice != null)
{
Voice.Speak(null, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
}
}
catch (Exception ex)
{
cGlobe_Log.Error(cGlobe_Log.GetMethodInfo() + ex.Message);
}
}
/// <summary>
/// 获取错误信息
/// </summary>
/// <param name="str"></param>
private void ErrInfo(Exception str)
{
if (this.ErrorInfoEvent != null)
{
this.ErrorInfoEvent(str);
}
}
#endregion ~WinSpeak()
{
try
{
if (Speak != null)
{
this.Speak.SpeakAsyncCancelAll();
this.Speak.Dispose();
}
}
catch (Exception exception)
{
//this.ErrInfo(exception);
}
}
}
}

1.2  调用如下(一个同步播放、一个异步播放):

   private void btnTest_Click(object sender, EventArgs e)
{
try
{
string strSep = txtWord.Text;
SFBR.WinSpeak._Init().Speech_SpeakText(strSep);
}
catch (Exception ex)
{ }
} private void button1_Click(object sender, EventArgs e)
{
try
{
string strSep = txtWord.Text;
SFBR.WinSpeak._Init().BeginSpeakText(strSep);
}
catch (Exception ex)
{ }
}

二、 最近客户提出需求需要在BS系统实现文字语音播放的功能,因不能接入外网不能调用第三方服务等,最后想到了一个解决方案:先把文字转化为音频文件,再把音频文件以流的形式推送到BS端进行播放;

2.1  同样可以利用微软自带的Speech语音播放库将一段文本转化为音频文件:

2.2 封装 SpeechService文字转换音频文件类

    public class SpeechService
{
private static SpeechSynthesizer synth = null;
/// <summary>
/// 返回一个SpeechSynthesizer对象
/// </summary>
/// <returns></returns>
private static SpeechSynthesizer GetSpeechSynthesizerInstance()
{
if (synth == null)
{
synth = new SpeechSynthesizer();
}
return synth;
}
/// <summary>
/// 保存语音文件
/// </summary>
/// <param name="text"></param>
public static void SaveMp3(string strFileName,string spText)
{
synth = GetSpeechSynthesizerInstance();
synth.Rate = ;
synth.Volume = ;
synth.SetOutputToWaveFile(strFileName);
synth.Speak(spText);
synth.SetOutputToNull();
}
}

2.3  接下来就是将音频文件以文件流的形式推送到前端播放:

  public async Task<ActionResult> PlayWav(string id,string spText)
{
string strPath = Server.MapPath("~\\MP4\\" + id + ".wav");
SpeechService.SaveMp3(strPath, spText);
try
{
using (FileStream fileStream = new FileStream(strPath, FileMode.Open))
{
byte[] fileByte = new byte[fileStream.Length];
fileStream.Seek(, SeekOrigin.Begin);
fileStream.Read(fileByte, , (int)fileStream.Length);
long fSize = fileStream.Length;
long startbyte = ;
long endbyte = fSize - ;
int statusCode = ;
if ((Request.Headers["Range"] != null))
{
//Get the actual byte range from the range header string, and set the starting byte.
string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
startbyte = Convert.ToInt64(range[]);
if (range.Length > && range[] != "") endbyte = Convert.ToInt64(range[]);
//If the start byte is not equal to zero, that means the user is requesting partial content.
if (startbyte != || endbyte != fSize - || range.Length > && range[] == "")
{ statusCode = ; }//Set the status code of the response to 206 (Partial Content) and add a content range header.
}
long desSize = endbyte - startbyte + ;
//Headers
Response.StatusCode = statusCode;
Response.ContentType = "audio/mpeg";
Response.AddHeader("Content-Accept", Response.ContentType);
Response.AddHeader("Content-Length", desSize.ToString());
Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
return File(fileByte, Response.ContentType); }
}
catch (Exception ex)
{
throw;
}
}

    注意:返回的必须为异步( async Task)不然会报错,因为文字音频转换涉及到异步调用

2.4 前端展示

2.5  运行截图如下:

BS实现文字音频调用demo地址如下:

  https://github.com/lxshwyan/SpeechBSDemo.git

CS程序和BS程序文字转语音的更多相关文章

  1. 使用 Android Studio 开发工具创建一个 Android 应用程序,显示一行文字“Hello Android”,并将应用程序的名称更改为“FirstApp”。

    需求说明: 使用 Android Studio 开发工具创建一个 Android 应用程序,显示一行文字"Hello Android",并将应用程序的名称更改为"Firs ...

  2. 简单C#文字转语音

    跟着微软走妥妥的,C#文字转语音有很多参数我就不说了,毕竟我也是初学者.跟大家分享最简单的方法,要好的效果得自己琢磨喽: 先添加引用System.Speech程序集: using System; us ...

  3. C# ms speech文字转语音例子

    最近突发奇想 想玩玩  文字转语音的东东   谷歌了一下 发现微软有一个TTS 的SDK   查了查相关资料  发现 还真不错  然后就开始玩玩Microsoft Speech SDK的 DEMO了 ...

  4. web端文字转语音的几种方案

    最近在开发一个微信排队取号的的系统,其中对于服务员端(管理端) 需要有呼叫功能,即点按钮 就播出"xxx号顾客请就座"的声音. 经过在网上一番搜索研究,web端实现指定文字的语音播 ...

  5. speech sdk 文字转语音

    1.下载SDK包 https://www.microsoft.com/en-us/download/details.aspx?id=10121 2.直接上代码 // SpeechRecognition ...

  6. springboot文字转语音(jacob)

    近期项目中出现在离线情况下文字转语音的需求 进过尝试返现jacob还不错 一下为开发记录: 1.pom.xml中引入jacob.jar <dependency> <groupId&g ...

  7. Web程序和应用程序服务器[转]

    转自:http://hi.baidu.com/lclkathy/blog/item/dae3be36763a47370b55a970.html 一 常见的WEB服务器和应用服务器 在UNIX和LINU ...

  8. 好程序与差程序Good Programming, Bad Programming

    好程序与差程序 Good Programming, Bad Programming 发布时间: 2012-11-20 16:32:21| 阅读数:2,735 views 优秀的程序可以使复杂的东西看起 ...

  9. 改善C#程序,提高程序运行效率的50种方法

    改善C#程序,提高程序运行效率的50种方法   转自:http://blog.sina.com.cn/s/blog_6f7a7fb501017p8a.html 一.用属性代替可访问的字段 1..NET ...

随机推荐

  1. 通通WPF随笔(1)——基于lucene.NET让ComboBox拥有强大的下拉联想功能

    原文:通通WPF随笔(1)--基于lucene.NET让ComboBox拥有强大的下拉联想功能 我一直很疑惑百度.谷哥搜索框的下拉联想功能是怎么实现的?是不断地查询数据库吗?其实到现在我也不知道,他们 ...

  2. x名称空间中的内容

    原文:x名称空间中的内容 x名称空间映射的是http://schemas.microsoft.com/winfx/2006/xaml,它包含的类均与XAML的解析有关,下面分三部分介绍 一:x名称空间 ...

  3. git/github初级运用自如 (good)

    三 . 设置用户信息 这一步不是很重要,貌似不设置也行,但github官方步骤中有,所以这里也提一下. 在git中设置用户名,邮箱 $ git config --global user.name &q ...

  4. wpf 快速建立可以拖动对象

    1.引用两个.net 程序集 2.xaml name space导入 xmlns:i ="http://schemas.microsoft.com/expression/2010/inter ...

  5. 微信小程序实战之百思不得姐精简版

    原文:微信小程序实战之百思不得姐精简版 微信小程序基本组件和API已撸完,总归要回到正题的,花了大半天时间做了个精简版的百思不得姐,包括段子,图片,音频,视频,四个模块.这篇就带着大家简述下这个小的A ...

  6. Delphi访问活动目录(使用COM,活动目录Active Directory是用于Windows Server的目录服务)

    活动目录Active Directory是用于Windows Server的目录服务,它存储着网络上各种对象的有关信息,并使该信息易于管理员和用户查找及使用.Active Directory使用结构化 ...

  7. [收录] Highcharts-ng —— AngularJS 的图表扩展

    原文:http://www.tuicool.com/articles/u6VZJjQ Highcharts-ng 是一个 AngularJS 的指令扩展,实现了在AngularJS 应用中集成High ...

  8. 关于 win32 下磁盘的遍历方法

    最近要写个在线专杀的东东,虽然是专杀(本来只要清除几个特定的文件和杀几个特定的进程,然后把用户的注册表恢复正常,很多病毒木马最喜欢干的一件事情就是写 映像劫持 然后机器一重启,安全相关的软件全部玩完了 ...

  9. jquery测试文档

    Jquery版本:* jQuery JavaScript Library v1.3.2 * http://jquery.com/ 引用:<script src="JS/jquery.j ...

  10. mybatis链接数据库

    DBTools类 public class DBTools { // 加载mybatis文件 public static SqlSession getSession() { //加载配置文件 Inpu ...