本文共 1844 字,大约阅读时间需要 6 分钟。
上篇博文说了一些Microsoft Speech Platform的知识点,这篇博文用一个例子来实践一下。
例子是实现一段文字的朗读,朗读到那一句文字,文字就变红色。就这么简单。
先看窗体布局。
实现代码:
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();}////// TTS对象/// SpeechSynthesizer speech;////// 分隔文本内容成数组/// /// 文本内容///字符数组 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;////// 播放内容/// 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;//朗读总长度////// 朗读Prompt开始时事件/// /// /// 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 + "句";}////// 朗读按钮/// /// /// private void Play_But_Click(object sender, EventArgs e){Play();}}}
转载地址:http://znidx.baihongyu.com/