using System;
namespace Helpers
{
public class TextSpeechHelper
{
private static TextSpeechHelper _instance;
private int? _rate;
private object _sync;
Type type;
private TextSpeechHelper()
{
_sync = new object();
}
static TextSpeechHelper()
{
_instance = new TextSpeechHelper();
}
private bool PlayText(string text)
{
lock (_sync)
{
type = Type.GetTypeFromProgID("SAPI.SpVoice");
try
{
dynamic spVoice = Activator.CreateInstance(type);
spVoice.Speak(text);
}
catch (Exception)
{
return false;
}
finally
{
if (type != null)
{
type = null;
}
}
}
return true;
}
private void SetRate(int rate)
{
int speechRate = rate;
speechRate = Math.Max(-10, rate);
speechRate = Math.Min(10, rate);
_rate = speechRate;
}
/// <summary>
/// 朗读文字
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool Play(string text)
{
return _instance.PlayText(text);
}
/// <summary>
/// 设置播放语速
/// </summary>
/// <param name="rate">{-10, 10}</param>
public static void SetRateValue(int rate)
{
_instance.SetRate(rate);
}
}
}