在用网上下载的例子学习基本操作的基础上,捣鼓了一个晚上,终于实现了调用TTS SDK朗读时获取当前词语的方法(中英文皆可)。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using SpeechLib; //引入语音
- using System.Threading;
- using System.Timers;
- namespace JcSpeak
- {
- public partial class Form1 : Form
- {
- Thread mythread;
- SpeechVoiceSpeakFlags svsf;
- //这里用的是SpVoice接口来实例化SpVoiceClass类,原来程序中是SpVoiceClass,但是没有Word事件
- SpVoice svc=null;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- richTextBox1.Text = "可以进行英文朗读;如果您想进行中文朗读,还需要下载并安装这两个文件是必需的,安装完这两个文件后,本程序就能进行中文朗读了。";
- svsf = SpeechVoiceSpeakFlags.SVSFDefault;
- svc = new SpVoiceClass();
- }
- //朗读
- private void Btn_Read_Click(object sender, EventArgs e)
- {
- mythread = new Thread(Voice);
- mythread.Start();
- //关键就是这句话了,增加了SpVoice.Word事件,可以在朗读中一直侦听当前朗读的词语
- svc.Word += new _ISpeechVoiceEvents_WordEventHandler(svc_Word);
- }
- void svc_Word(int StreamNumber, object StreamPosition, int CharacterPosition, int Length)
- {
- richTextBox1.Select(CharacterPosition, Length);
- richTextBox1.SelectionColor = Color.Blue;
- throw new NotImplementedException();
- }
- private void Voice()
- {
- svc.Speak(richTextBox1.Text.Trim(), svsf);
- mythread.Abort();
- }
- //暂停
- private void Btn_Pause_Click(object sender, EventArgs e)
- {
- svc.Pause();
- }
- //继续
- private void Btn_Resume_Click(object sender, EventArgs e)
- {
- svc.Resume();
- }
- //停止
- private void Btn_Stop_Click(object sender, EventArgs e)
- {
- svc.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
- }
- }
- }
简单的效果图
心得:
1、首先是本文的主角,SpVoice中的Word事件。文档中的描述是这样的
Microsoft Speech SDK
Speech Automation 5.1
Object: SpVoice (Events)
Word Event
The Word event occurs when the text-to-speech (TTS) engine detects a word boundary while speaking a stream for the SpVoice object.
SpVoice.Word( StreamNumber As Long, StreamPosition As Variant, CharacterPosition As Long, Length As Long )
Parameters
- StreamNumber
- The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
- StreamPosition
- The character position in the output stream at which the word begins.
- CharacterPosition
- The character position in the input stream one character before the start of the word. In the case of the first word in a stream, this parameter is zero.
- Length
- The length of the word in the input stream.
英文很烂,就不翻译了。可见,获取当前朗读的词语就是靠CharacterPosition和Length两个参数。
2、一直没能解决的是SpVoice的停止问题。很多例子里面都是(包括自己这个)
- svc.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
但是一点停止按钮程序就死了,幸好暂停功能还是可以用的,只好先用暂停代替着。