vb.net SpeechLib 播报语音封装类

vb.net 使用SpeechLib 播报汉字语音,如果第一句没说完就让它说第二句,可以中止前一句,也可以等前一句说完再说第二句。调用Skip方法即可。

先引用microsoft speech lib object library。

封装实现:


Imports SpeechLib
Imports System.Threading

Public Class Speaker
	Private ReadOnly Speaker As New SpVoice

	Public Property Volume() As Int16 = 100
	Public Property Rate() As Int16 = 0

	Public Sub Speak(Content As String, enginee As String)
		Dim t As Thread
		t = New Thread(AddressOf Speak)
		t.IsBackground = True
		t.Start(New String(1) {Content, enginee})
	End Sub

	Public Sub Speak(param() As String)
		Dim Voices As ISpeechObjectTokens = Speaker.GetVoices()
		Dim cnVoice As Integer = -1

		If (Voices.Count = 0) Then
			Debug.Print("没有安装语音引擎")
			Exit Sub
		End If

		For i = 0 To Voices.Count - 1
			If Right(Voices.Item(i).GetDescription, Len(param(1))) = param(1) Then
				cnVoice = i
				Exit For
			End If
		Next

		If cnVoice < 0 Or cnVoice > Voices.Count - 1 Then
			Debug.Print("指定的语音引擎不存在")
			Exit Sub
		End If

		Speaker.Voice = Voices(cnVoice)
		Speaker.Rate = Rate
		Speaker.Volume = Volume
		Speaker.Skip("Sentence", 1)    '终止前一句
		Speaker.Speak(param(0), SpeechVoiceSpeakFlags.SVSFlagsAsync)   '异步参数,防止卡住

	End Sub
End Class

如何调用:

窗体准备两个按钮,两个文本框。一个combobox

Imports SpeechLib

Public Class Form1
	Dim speaker As New Speaker
	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

		speaker.Rate = -10
		speaker.Volume = 100

		speaker.Speak(TextBox1.Text, ComboxVoice.Text)


	End Sub

	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
		Dim Speaker As New SpVoice
		Dim Voices As ISpeechObjectTokens = Speaker.GetVoices()
		For Each x As ISpeechObjectToken In Voices
			ComboxVoice.Items.Add(x.GetDescription)
		Next
		If ComboxVoice.Items.Count > 0 Then
			ComboxVoice.SelectedIndex = 0
		End If

	End Sub

	Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
		speaker.Rate = 10
		speaker.Volume = 100
		speaker.Speak(TextBox2.Text, ComboxVoice.Text)
	End Sub
End Class

点一个按钮,然后接着点第二个按钮,测试一下能不能中断第一句话接着说第二句话。如果不想中断,把类里面的_Speaker.Skip("Sentence", 1)    这句代码删除即可。

你可能感兴趣的:(vb.net)