winform 图灵机器人加Speech语音播报库

winform 图灵机器人加Speech语音播报库

1.添加引用,添加微软自带的Speech

winform 图灵机器人加Speech语音播报库_第1张图片

2.新建一个winform页面

winform 图灵机器人加Speech语音播报库_第2张图片

页面比较简陋,可以适当添加部分功能

3.初始化一个SpVoice 对象

SpVoice SpVoice = new SpVoice();
//语速
SpVoice.Rate = 2;
//音量
SpVoice.Volume = 80;
//语音库
SpVoice.Voice = SpVoice.GetVoices().Item(0);

4.发送信息

/// 
/// 发送按钮
/// 
/// 
/// 
private void SendOut_Click(object sender, EventArgs e)
{
    //获取发送区
    String input = tbxInput.Text;
    //接口返回值{"code":100000,"text":"对不起,没听清楚,请再说一遍吧。"}
    //KEY为自己在图灵注册key
    string url = "http://www.tuling123.com/openapi/api?key=" + KEY + "&info=" + input;
    //发送区清空
    tbxInput.Text = "";
    //接受区添加文本
    tbxHistory.AppendText("You: " + input + "\n");
    //Encoding为编码类型
    Encoding encoding = Encoding.GetEncoding("utf-8");

    String data = HttpGets(url, encoding);
    //转json格式
    JsonReader reader = new JsonTextReader(new StringReader(data));

    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.PropertyName
            && reader.ValueType == Type.GetType("System.String")
            && Convert.ToString(reader.Value) == "code")
        {
            reader.Read();
            switch (Convert.ToInt32(reader.Value))
            {
                case 100000:
                    reader.Read();
                    //接受区添加文本
                    tbxHistory.AppendText("阿旺呀: " + reader.Value + "\n");
                    //播报文字
                    SpVoice.Speak(reader.Value.ToString());
                    break;
                default:
                    break;
            }
        }
    }
}

5.请求接口的方法

/// 
/// 请求接口
/// 
/// 链接
/// 编码类型
/// 
public static string HttpGets(string url, Encoding encoding)
{
    string data = "";
    try
    {
        //使用url发出请求的对象
        WebRequest request = WebRequest.Create(url);
        //使用默认的身份验证
        request.Credentials = CredentialCache.DefaultCredentials;
        //设定超时时间
        request.Timeout = 10000;
        //提供响应的对象
        WebResponse response =request.GetResponse();
        //获取数据
        data = new StreamReader(response.GetResponseStream(), encoding).ReadToEnd();    
    }
    catch (System.Exception e)
    {
        Console.WriteLine(e.Message);
    }

    return data;
}

关于语音输入的功能,我还在研究中,有兴趣的朋友可以给我提些实用的功能,我慢慢研究下

你可能感兴趣的:(c#)