[fix]修正UdpServer在接收广播时连续启动接收的错误,在StarAgent中,此时可能收到广播包,SocketFlags是Broadcast,需要清空,否则报错“参考的对象类型不支持尝试的操作”; 无需设置SocketOptionName.PacketInformation,在ReceiveMessageFromAsync时会自动设置,并且支持ipv6;
石头 编写于 2024-10-10 00:36:00 石头 提交于 2024-10-10 00:45:43
X
using System.Reflection;
using NewLife.Log;
using NewLife.Reflection;

namespace NewLife.Extension;

class SpeakProvider
{
    private static readonly String typeName = "System.Speech.Synthesis.SpeechSynthesizer";
    private Type? _type;

    public SpeakProvider()
    {
        try
        {
            //_type = typeName.GetTypeEx(true);
            _type = Type.GetType(typeName);
            if (_type == null)
            {
                Assembly? asm = null;
                try
                {
                    // 新版系统内置
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        asm ??= Assembly.Load("System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                    }
                }
                catch { }
                try
                {
                    asm ??= Assembly.Load("System.Speech");
                }
                catch { }
                _type = asm?.GetType(typeName);
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
        }

        if (_type == null) XTrace.WriteLine("找不到语音库System.Speech,需要从nuget引用");
    }

    private Object? synth;
    void EnsureSynth()
    {
        if (synth == null && _type != null)
        {
            try
            {
                synth = _type.CreateInstance(new Object[0]);
                synth?.Invoke("SetOutputToDefaultAudioDevice", new Object[0]);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                _type = null;
            }
        }
    }

    public void Speak(String value)
    {
        if (_type == null) return;

        EnsureSynth();
        synth?.Invoke("Speak", value);
    }

    public void SpeakAsync(String value)
    {
        if (_type == null) return;

        EnsureSynth();
        synth?.Invoke("SpeakAsync", value);
    }

    /// <summary>
    /// 停止话音播报
    /// </summary>
    public void SpeakAsyncCancelAll()
    {
        if (_type == null) return;

        EnsureSynth();
        synth?.Invoke("SpeakAsyncCancelAll");
    }
}