您的位置:时时app平台注册网站 > 编程知识 > C# 控制台语音计算器

C# 控制台语音计算器

2019-10-30 04:40

技术探讨群:225443677 有意者款待打扰,多谢!

转发请申明出处www.codegize.com

2.其次,别忘了援用下那五个命名空间:

/*轻松易行的SAPI语音合成调整台程序*/

哈哈哈,作者正是分外带点儿逗比的搬砖员儿!好吧,代码来了,小主,等急了吧?

using System.Diagnostics;

public class Speecher: MonoBehaviour
{
    public static void Speak(string str)
    {
        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "speech.exe",
                Arguments = """   str   """,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
            }
        };
        proc.Start();
    }
    /***测试代码,可删除Start***/
    protected void Start()
    {
        Speak("test");
    }
    /***测试代码,可删除End***/
}

“哎哎作者去,非逼本身说粗话,来个货,把代码码上来!”

/*可见配置的调节台程序*/

寻寻找觅,销声匿迹,凄悲凉惨戚戚!什么?没搜索到?

唯独要是做过那地点开垦的精晓,在C#的其它使用里面引用System.Speech.dll是全然没十分的。那么是或不是大家能够支付多少个特别的第三方前后相继,然后unity实行调用呢?根据这一个思路,大家付出了三个调节台程序Speech.exe,首要功用是依照输入文本进行语音合成。

好啊,介绍下这么些类库,它叫“System.Speech.dll”。.net FrameWork 的装置目录里就有它的人影!装了.net FrameWork 的童鞋,能够经过以下目录去寻找它!

小编们先接收CMD命令行,cd到Speech.exe所在的目录,然后输入Speech.exe test,如作者辈预料的那么,机器发音test。测验通过。

using System;
using System.Speech.Synthesis;
using System.Collections.Generic;

namespace ReadTxt
{
    class Program
    {

        static string num1 = "", firchar = "", lastchar = "", tempRe = "";

        static void Main(string[] args)
        {

            Console.Title = "语音计算器";
            bool jump = true;
            do
            {

                ConsoleKeyInfo info = Console.ReadKey();
                switch (info.Key)
                {
                    case ConsoleKey.Escape: Environment.Exit(0); jump = false; break;
                    case ConsoleKey.NumPad0:    GetKeyRead("0");     break;
                    case ConsoleKey.NumPad1:    GetKeyRead("1");     break;
                    case ConsoleKey.NumPad2:    GetKeyRead("2");     break;
                    case ConsoleKey.NumPad3:    GetKeyRead("3");     break;
                    case ConsoleKey.NumPad4:    GetKeyRead("4");     break;
                    case ConsoleKey.NumPad5:    GetKeyRead("5");     break;
                    case ConsoleKey.NumPad6:    GetKeyRead("6");     break;
                    case ConsoleKey.NumPad7:    GetKeyRead("7");     break;
                    case ConsoleKey.NumPad8:    GetKeyRead("8");     break;
                    case ConsoleKey.NumPad9:    GetKeyRead("9");     break;
                    case ConsoleKey.Add:        GetKeyRead("加");    break;
                    case ConsoleKey.Subtract:   GetKeyRead("减");    break;
                    case ConsoleKey.Multiply:   GetKeyRead("乘");    break;
                    case ConsoleKey.Divide:     GetKeyRead("除");    break;
                    case ConsoleKey.Enter:
                        if (!string.IsNullOrEmpty(num1) && GetSignIsTrue(num1))
                        {
                            SetValue(num1);
                            num1 = "";
                        }
                        else
                        {
                            num1 = "";
                            if (!string.IsNullOrEmpty(num1))
                            {
                                Console.Beep();
                                Console.WriteLine("Error.");
                            }
                        }
                        break;
                    default:
                        break;
                }
            } while (jump);
            Console.Read();
        }

        //判断用户输入的内容是否合法
        static void GetKeyRead(string str)
        {
            SpeechSynthesizer spvoice = new SpeechSynthesizer();
            spvoice.Rate = 1;
            spvoice.Volume = 100;

            if (!string.IsNullOrEmpty(num1))
            {
                firchar = num1.Substring(0, 1);
                lastchar = num1.Substring(num1.Length - 1, 1);
            }

            switch (str)
            {
                case "加":
                    if (firchar != "加" && lastchar != "加")
                    {
                        if (lastchar != "减" && lastchar != "乘" && lastchar != "除")
                        {
                            num1  = str;
                        }
                        else
                        {
                            num1 = num1.Remove(num1.Length - 1);
                            num1  = str;
                        }
                    }

                    break;
                case "减":
                    if (firchar != "减" && lastchar != "减")
                    {
                        if (lastchar != "加" && lastchar != "乘" && lastchar != "除")
                        {
                            num1  = str;
                        }
                        else 
                        {
                            num1 = num1.Remove(num1.Length - 1);
                            num1  = str;
                        }
                    }

                    break;
                case "乘":
                    if (firchar != "乘" && lastchar != "乘")
                    {
                        if (lastchar != "加" && lastchar != "减" && lastchar != "除")
                        {
                            num1  = str;
                        }
                        else
                        {
                            num1 = num1.Remove(num1.Length - 1);
                            num1  = str;
                        }
                    }
                    break;
                case "除":
                    if (firchar != "除" && lastchar != "除")
                    {
                        if (lastchar != "加" && lastchar != "减" && lastchar != "乘")
                        {
                            num1  = str;
                        }
                        else
                        {
                            num1 = num1.Remove(num1.Length - 1);
                            num1  = str;
                        }
                    }
                    break;
                default:
                    num1  = str;
                    break;
            }
            spvoice.SpeakAsync(str);
            Console.Clear();
            Console.Write(tempRe   num1.Replace('加', ' ').Replace('减', '-').Replace('乘', '*').Replace('除', '/').Replace("等于", "="));
        }

        static bool GetSignIsTrue(string num1) 
        {
            if (!string.IsNullOrEmpty(num1))
            {
                firchar = num1.Substring(0, 1);
                lastchar = num1.Substring(num1.Length - 1, 1);
            }

            return firchar != "加" && lastchar != "加" && firchar != "减" && lastchar != "减" && firchar != "乘" && lastchar != "乘" && firchar != "除" && lastchar != "除";
        }

        //计算
        static void SetValue(string num1)
        {
            List<double> array = new List<double>();
            List<string> sign = new List<string>();
            num1 = num1.Replace('加', ' ').Replace('减', '-').Replace('乘', '*').Replace('除', '/');
            string tempCap = "";
            char[] MyChar = num1.ToCharArray();
            for (int i = 0; i < MyChar.Length; i  )
            {
                if (MyChar[i].ToString() == " " || MyChar[i].ToString() == "-" || MyChar[i].ToString() == "*" || MyChar[i].ToString() == "/")
                {
                    array.Add(Convert.ToDouble(tempCap));
                    tempCap = "";
                    sign.Add(MyChar[i].ToString());
                }
                else
                {
                    if (i == MyChar.Length - 1)
                    {
                        tempCap  = MyChar[i].ToString();
                        array.Add(Convert.ToDouble(tempCap));
                    }
                    else
                    {
                        tempCap  = MyChar[i].ToString();
                    }
                }
            }

            double resultTemp = 0;
            for (int i = 0; i < sign.ToArray().Length; i  )
            {
                if (sign[i] == "*")
                {
                    resultTemp = array[i] * array[i   1];
                    array[i] = resultTemp;
                    array.Remove(array[i   1]);
                    sign.Remove(sign[i]);
                    resultTemp = 0;
                    i--;
                }
                else if (sign[i] == "/")
                {
                    resultTemp = array[i] / array[i   1];
                    array[i] = resultTemp;
                    array.Remove(array[i   1]);
                    sign.Remove(sign[i]);
                    resultTemp = 0;
                    i--;
                }
            }

            for (int i = 0; i < sign.ToArray().Length; i  )
            {
                if (sign[i] == " ")
                {
                    resultTemp = array[i]   array[i   1];
                    array[i] = resultTemp;
                    array.Remove(array[i   1]);
                    sign.Remove(sign[i]);
                    resultTemp = 0;
                    i--;
                }
                else if (sign[i] == "-")
                {
                    resultTemp = array[i] - array[i   1];
                    array[i] = resultTemp;
                    array.Remove(array[i   1]);
                    sign.Remove(sign[i]);
                    resultTemp = 0;
                    i--;
                }
            }

            double answ = array[0];
            array.Clear();
            sign.Clear();
            tempRe  = num1.Replace('加', ' ').Replace('减', '-').Replace('乘', '*').Replace('除', '/')   "= "   answ   "n";
            GetKeyRead("等于"   answ);
        }
    }
}
using System;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using Speech.Properties;

namespace Speech
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new NetServer();
            server.StartServer();

            while (true)
            {
                var res = Console.ReadLine();
                if (res == "exit")
                    break;
            }
        }
    }

    public class NetServer : SocketExtra.INetComponent
    {
        private readonly Speecher m_speecher;

        private readonly SocketExtra m_socket;

        public NetServer()
        {
            m_speecher = new Speecher();
            m_socket = new SocketExtra(this);
        }

        public void StartServer()
        {
            m_socket.Bind("127.0.0.1", Settings.Default.Port);
        }

        public bool NetSendMsg(byte[] sendbuffer)
        {
            return true;
        }

        public bool NetReciveMsg(byte[] recivebuffer)
        {
            var str = Encoding.Default.GetString(recivebuffer);
            Console.WriteLine(str);
            m_speecher.Speak(str);
            return true;
        }

        public bool Connected { get { return m_socket.Connected; } }
    }

    public class Speecher
    {
        private readonly SpeechSynthesizer m_speaker;

        public Speecher()
        {
            m_speaker = new SpeechSynthesizer();
            var installs = m_speaker.GetInstalledVoices();

            m_speaker.Volume = Settings.Default.SpeakVolume;
            m_speaker.Rate = Settings.Default.SpeakRate;
            var voice = Settings.Default.SpeakVoice;

            var selected = false;
            if (!string.IsNullOrEmpty(voice))
            {
                if (installs.Any(install => install.VoiceInfo.Name == voice))
                {
                    m_speaker.SelectVoice(voice);
                    selected = true;
                }
            }
            if (!selected)
            {
                foreach (var install in installs.Where(install => install.VoiceInfo.Culture.Name == "en-US"))
                {
                    m_speaker.SelectVoice(install.VoiceInfo.Name);
                    break;
                }
            }
        }

        public void Speak(string msg)
        {
            m_speaker.Speak(msg);
        }
    }
}

好了,其余的代码就要看小主的内力了,在下就不多说了!

Windows的长河是并行独立的,各有各的分红空间。但是并不意味着那不能够互相通讯。方法有数不完,举例读写文件,发送消息(hook),Socket等等。个中Socket完结起来相对简单,特别是我们早就具有Socket封装库的情事下,只要一些些代码就行了。

拙文大器晚成篇,望各位海涵!

/*Speech 服务端*/

图片 1

using System.Speech.Synthesis;
using SpeechTest.Properties;

namespace SpeechTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var speaker = new SpeechSynthesizer();
            var res = args.Length == 0 ? "请说" : args[0];
            speaker.Speak(res);
        }
    }
}

  using System.Collections.Generic;  //数组会集类库

using System.Speech.Synthesis;
using SpeechTest.Properties;

namespace SpeechTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var speaker = new SpeechSynthesizer();
            speaker.Speak(“test”);
        }
    }
}

其实,也就几句话!

于是乎在Speech改成三个Socket服务器,代码如下:

后天在做一个品种,有个简易的机能,正是将文件转变来语音。

using System.Collections;
using System.Diagnostics;
using System.Text;
using UnityEngine;

public class Speecher : MonoBehaviour, SocketExtra.INetComponent
{
    private SocketExtra m_socket;
    private Process m_process;

    protected void Awake()
    {
        Ins = this;
        m_process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "speech.exe",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden
            },
        };
        m_process.Start();
    }

    /***测试代码,可删除Start***/
    protected IEnumerator Start()
    {
        yield return StartCoroutine(Connect());
        Speak("test");
    }
    /***测试代码,可删除End***/

    public IEnumerator Connect()
    {
        m_socket = new SocketExtra(this);
        m_socket.Connect("127.0.0.1", 9903);
        while (!m_socket.Connected)
        {
            yield return 1;
        }
    }

    protected void OnDestroy()
    {
        if (m_process != null && !m_process.HasExited)
            m_process.Kill();
        m_process = null;
    }

    public static Speecher Ins;

    public static void Speak(string str)
    {
#if UNITY_EDITOR||UNITY_STANDALONE_WIN
        Ins.Speech(str);
#endif
    }

    public void Speech(string str)
    {
        if (m_socket.Connected)
        {
            var bytes = Encoding.Default.GetBytes(str);
            m_socket.SendMsg(bytes);
        }
    }

    public bool NetReciveMsg(byte[] recivebuffer)
    {
        return true;
    }

    public bool NetSendMsg(byte[] sendbuffer)
    {
        return true;
    }
}

找到的,直接引用到花色里就行了哈!

/*Unity开启无框的Speech.exe进程*/

SpeechSynthesizer spvoice = new SpeechSynthesizer();  //语音类
spvoice.Rate = 1;            //使用 spvoice 设置朗读频率 [范围 -10 ~ 10] 
spvoice.Volume = 80;         //使用 spvoice 设置朗读音量 [范围 0 ~ 100] 
spvoice.SpeakAsync("大家好,我是博主小白!");   //开始读
using System.Speech.Synthesis;
using SpeechTest.Properties;

namespace SpeechTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var speaker = new SpeechSynthesizer();
            speaker.Volume = Settings.Default.SpeakVolume;
            speaker.Rate = Settings.Default.SpeakRate;
            var voice = Settings.Default.SpeakVoice;
            if (!string.IsNullOrEmpty(voice))
                speaker.SelectVoice(voice);
            var res = args.Length == 0 ? "请说" : args[0];
            speaker.Speak(res);
        }
    }
}

“好的,老大!”

/*Unity客户端代码*/

“来银啊,上代码!”

将脚本挂在其他三个GO(GameObject)上,运维,黑框现身,同不经常候听到发音,测验完了。

 

应用SAPI,供给选择到的是System.Speech.dll文件。由于Unity须求将Dll文件放在Asset目录下,而那样的结果会意识sapi failed to initialize。原因质疑为急需一定的上下文处境本事运转dll的api,以致于拷贝到Asset目录导致上下文境遇缺失而一点战略也施展不出运维。

看小主骨骼惊喜,“匈牙利(Hungary)语优质”,想是定能习得搬砖精华,打遍天下须要,杀掉尘间bug;然后走上淫僧巅峰,赢取大白美人的!哈哈哈~!

同不常间改过Unity代码,扩展Socket相关代码:

 

OK,水到渠成。工程见Github图片 2

其实,语音作用完结起来并不复杂,微软早已封装好了多个,将文件调换到语音功能的类库,以后您要做的就是:找到它,然后把它援引到您的连串里!

怎么?那些类库叫什么?

接下去大家隐蔽那个黑框。代码矫正如下:

1.既然是语音总计器,首先要消除的正是怎么贯彻语音?

大家改过一下,改为从参数中读取,那样的话,我们得以在unity中央银行使Process运营Speech.exe,并传给Speech参数。

3.结尾,简单介绍下文件调换来语音的成效!

为了能够转移发音的陈设,扩大部分代码,从Setting中读取相关的铺排数据,代码匡正如下:

正是因为这些,才对语音总括器有了浓厚印象!恐怕是那货坑了本人!哼~!

在VWrangler开采进程中,由于运营在Windows处境下,那么任天由命,大家首荐SAPI来举行语音开拓。一是和Windows原生,二是离线无需网络,三是无需别的插件。别的正是SAPI发音,越发是保加利亚语发音,照旧相对来讲品质不错的。(Win7上述自带)

表急嘛,心急吃不了“热水豆腐”,有异常的大或许“豆腐”还跑了吧,要耐烦点儿,才具约到手!是吗?

代码较为轻巧

  using System.Speech.Synthesis;  //语音类库

/*从参数读取供给发声的文书*/

“老大,木有银,上不了”

/*Unity中开启Speech.exe进程*/

 

using System.Diagnostics;

public class Speecher: MonoBehaviour
{
    public static void Speak(string str)
    {
        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "speech.exe",
                Arguments = """   str   """,
            }
        };
        proc.Start();
    }

    /***测试代码,可删除Start***/
    protected void Start()
    {
        Speak("test");
    }
    /***测试代码,可删除End***/
}

开发C盘,间接寻找!

OK,运行就可以听见机器发音Test了。

ok,那就是整个代码了,请容在下粗略的介绍下促成步骤:

软件中的语音技能主要蕴涵二种:语音识别speech recognition和话音合成speech synthesis。平时地,开垦者会因为技巧实力和花费实力等外地点的标题无力实现专门的学问的语音引擎,由此普通选用现存的较为专门的学问的话音引擎来成功相关的开销,比如本国十一分知名的中国科学技术大学讯飞,百度语音等等。当然国外的还也可能有Google语音,微软有SAPI等等。

好呢,教您生机勃勃招

骨子里到了这一步,重要的功力都做到了。然则留心的会发觉,那样不断创建进度然后关门进度的方法会不会太笨了。行还是不行让Speech那些历程一向敞开着,收到unity的消息时就嚷嚷呢?那就提到到进度间通讯了。

行吗,闲言少叙,直入正题吧!

接下去大家在Unity中运用Process来展开那些Speech.exe,代码如下:

回想上高级中学时,给人超越生,支持买下账单月度工资;用的正是带语音功能的总结器! 那时用起来倍儿爽,于是速度加倍,功效加快;结果让高管赔了超多钱!

琢磨了那一个效应后,抽空顺带做了个语音计算器!

没装的,这就去互连网搜吧,自个儿下崽儿!哈哈~!愿意装的也得以装一下!

大概是那个:C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5

本文由时时app平台注册网站发布于编程知识,转载请注明出处:C# 控制台语音计算器

关键词: