Microsoft Speech Platform案例

文字朗读变色示例
本示例演示了如何使用Microsoft Speech Platform实现在朗读过程中改变当前朗读文字的颜色。通过将文本分隔并逐句朗读,同时更改富文本框中对应句子的颜色,以视觉方式辅助用户跟踪朗读进度。

上篇博文说了一些Microsoft Speech Platform的知识点,这篇博文用一个例子来实践一下。

例子是实现一段文字的朗读,朗读到那一句文字,文字就变红色。就这么简单。

先看窗体布局。

104250966.png

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
using  System.Windows.Forms;
using  Microsoft.Speech.Synthesis;
using  System.Threading;
namespace  SpeechPro
{
public  partial  class  PlayForm : Form
{
public  PlayForm()
{
InitializeComponent();
}
/// <summary>
/// TTS对象
/// </summary>
SpeechSynthesizer speech;
/// <summary>
/// 分隔文本内容成数组
/// </summary>
/// <param name="content">文本内容</param>
/// <returns>字符数组</returns>
string [] GetArr( string  content)
{
char [] charArr =  new  char [] {  '。' ',' ';'  }; //分隔字符数组
string [] arr = content.Split(charArr, StringSplitOptions.RemoveEmptyEntries); //分隔
int  sumcount = 0; //字符总数变量
for  ( int  i = 0; i < arr.Length; i++)
{
sumcount += arr[i].Length; //累加变量总数
arr[i] += content.Substring(sumcount, 1); //获取分隔标点符号
sumcount += 1; //加标点符号的长度
}
return  arr;
}
string [] arr;
/// <summary>
/// 播放内容
/// </summary>
void  Play()
{
arr = GetArr(Play_TB.Text);
//设计TTS对象,并设置对象
speech =  new  SpeechSynthesizer();
speech.SetOutputToDefaultAudioDevice();
speech.Volume = 100;
speech.Rate = 0;
speech.SpeakStarted += speech_SpeakStarted;
//异步诵读语音
for  ( int  i = 0; i < arr.Length; i++)
{
PromptBuilder pb =  new  PromptBuilder();
pb.AppendText(arr[i], PromptRate.Medium);
Prompt p =  new  Prompt(pb);
speech.SpeakAsync(p);
}
}
int  index = 0; //朗读索引值
int  sum = 0; //朗读总长度
/// <summary>
/// 朗读Prompt开始时事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void  speech_SpeakStarted( object  sender, SpeakStartedEventArgs e)
{
if  (index > 0)
{
//使上一条记录恢复原来的样式
Play_TB.Select(sum - arr[index - 1].Length, arr[index - 1].Length);
Play_TB.SelectionColor = Color.Black;
}
//设置现在朗读记录的样式
Play_TB.Select(sum, arr[index].Length);
Play_TB.SelectionColor = Color.Red;
//增加长度和朗读索引
sum += arr[index].Length;
index++;
this .Text =  "正在朗读第"  + index +  "句" ;
}
/// <summary>
/// 朗读按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private  void  Play_But_Click( object  sender, EventArgs e)
{
Play();
}
}
}

 
















本文转自桂素伟51CTO博客,原文链接: http://blog.51cto.com/axzxs/1247881,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值