Microsoft Speech Platform案例
上篇博文说了一些MicrosoftSpeechPlatform的知识点,这篇博文用一个例子来实践一下。
例子是实现一段文字的朗读,朗读到那一句文字,文字就变红色。就这么简单。
先看窗体布局。
实现代码:
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();}}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。