开发者

C# SpeechSynthesizer makes service unresponsive

开发者 https://www.devze.com 2023-02-03 16:53 出处:网络
I have the f开发者_JAVA技巧olowing code [WebMethod] public byte[] stringToWav(string text) { SpeechSynthesizer ss = new SpeechSynthesizer();

I have the f开发者_JAVA技巧olowing code

[WebMethod]
public byte[] stringToWav(string text)
{
    SpeechSynthesizer ss = new SpeechSynthesizer();
    MemoryStream ms = new MemoryStream();
    ss.SetOutputToWaveStream(ms);
    ss.Speak(text);
    return ms.ToArray();
}

and the service returns nothing. Any idea why this happens?


I ran into the same exact problem with an ashx page.

I don't understand exactly why, but it seems that you need to use a separate thread and wait for it to complete.

The following code worked for me:

public byte[] TextToBytes(string textToSpeak)
{
    byte[] byteArr = null;

    var t = new System.Threading.Thread(() =>
    {
        SpeechSynthesizer ss = new SpeechSynthesizer();
        using (MemoryStream memoryStream = new MemoryStream())
        {
            ss.SetOutputToWaveStream(memoryStream);
            ss.Speak(textToSpeak);
            byteArr = memoryStream.ToArray();
        }
    });
    t.Start();
    t.Join();
    return byteArr;
}


Have you debugged and checked the value of ms.ToArray()? You might have better luck with ms.ToByteArray().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号