在使用微软语音合成动态库SpeechLib时,发现一个问题,就是使用过程中发内存在不断增加,在实际应用中,大概经过2000多次的,catch异常:
Exception of type 'System.OutOfMemoryException' was thrown.我也百度过,一位仁兄提到过此问题,但是回答说这个问题无解,给出的方案是只能过一段时间,重启程序,这也是一个不得已方法。有没有s什么很好的解决方法呢?求教各位高手?贴源代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpeechLib;
namespace SimpleTTS
{
public class TtsController:ITts
{
private readonly SpVoice _SPVoice;
private readonly SpeechVoiceSpeakFlags _SpFlags ;
public TtsController()
{
if (_SpFlags == null)
_SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
if (_SPVoice == null)
_SPVoice = new SpVoice();
_SPVoice.Rate = -1;
string LibVoice = "Microsoft Lili - Chinese (China)";
ISpeechObjectTokens obj = _SPVoice.GetVoices();
int count = obj.Count;//获取语音库总数
for (int i = 0; i < count; i++)
{
string desc = obj.Item(i).GetDescription(); //遍历语音库
if (desc.Equals(LibVoice))
{
_SPVoice.Voice = obj.Item(i);
break;
}
}
}
public void Speak(string text)
{
try
{
_SPVoice.Speak(text, _SpFlags);
}
catch (Exception ex)
{
throw ex;
}
}
public void Resume()
{
try
{
_SPVoice.Resume();
}
catch (Exception ex)
{
throw ex;
}
}
public void Stop()
{
try
{
_SPVoice.Pause();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
调用:
private readonly object _lock_vioce = new object();
private TtsController TTSControllers = new TtsController();
///
/// 播放文字的语音
///
///
private void Speaker(object obj)
{
lock (_lock_vioce)
{
string text = (string)obj;
TTSControllers.Speak(text);
}
}
for(int i=0;i<10000;i++)
{
try
{
Thread thread_voice = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Speaker));
thread_voice.IsBackground = true;
thread_voice.Start("你好");
Thread.Sleep(1000);
Application.DoEvents();
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
}