Microsoft Speech Platform案例

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

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

先看窗体布局。

104250966.png

实现代码:

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();
}
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值