unity 接百度基础翻译

1.上百度翻译开放平台注册账号

2.unity接入json解析的相关dll文件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using UnityEngine.UI;

public class LanguageTool1 :MonoBehaviour
{
    //可以直接到百度翻译API的官网申请
    //一定要去申请,不然程序的翻译功能不能使用
    private static string appId = "20190724000321073";
    private static string password = "74HzbIN_uKglcHJoRSsS";

    //button_arr
    public Button[] button_arr;
    public InputField wen_arr;
    
    public  GameObject wen_show;
 

    private Dictionary<string, Dictionary<int, string>> dic = new Dictionary<string, Dictionary<int, string>>();

    string sourceStr;
    string id = "";
    //开始
    private void Start()
    {
        
        for (int i = 0; i < button_arr.Length; i++)
        {
            int temp = i;

            button_arr[temp].onClick.AddListener(delegate () { Set_event(button_arr[temp].name); } );
        }
    }
    public void Set_event(string str)
    {
        sourceStr = wen_arr.text;
        switch (str)
        {
            case "英文":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.en,"英语");
                break;
            case "阿拉伯":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.ara, "阿拉伯");
                break;
            case "法语":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.fra, "法语");
                break;
            case "德语":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.de, "德语");
                break;
            case "葡萄牙":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.pt, "葡萄牙");
                break;
            case "俄语":
                GetTranslationFromBaiduFanyi(id, sourceStr, Language.zh, Language.ru, "俄语");
                break;
           
        }
     
    }


    private  TranslationResult GetTranslationFromBaiduFanyi(string id, string q, Language from, Language to, string language = "")
    {

        string jsonResult = String.Empty;
        //源语言
        string languageFrom = from.ToString().ToLower();
        //目标语言
        string languageTo = to.ToString().ToLower();
        //随机数
        string randomNum = System.DateTime.Now.Millisecond.ToString();
        //md5加密
        string md5Sign = GetMD5WithString(appId + q + randomNum + password);
        //url
        string url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}",
            q,
            languageFrom,
            languageTo,
            appId,
            randomNum,
            md5Sign
            );
        WebClient wc = new WebClient();
        try
        {
            jsonResult = wc.DownloadString(url);
          
        }
        catch
        {
            jsonResult = string.Empty;
        }
        //结果转json
        TranslationResult temp = LitJson.JsonMapper.ToObject<TranslationResult>(jsonResult);
        
        if (null != temp)
        {
            //print(temp.trans_result[0].dst);
            if (string.IsNullOrEmpty(language))
            {
                //for (int i = 0; i < temp.trans_result.Length; i++)
                //{
                    string str = @"{""Key"":" + id + @",""Content"":" + @"""" + temp.trans_result[0].dst + @"""" + "},";
                // Debug.LogError(str);
                //print(str);
                wen_show.GetComponent<Text>().text = temp.trans_result[0].dst;
            //}
        }
            else
            {
                //for (int i = 0; i < temp.trans_result.Length; i++)
                //{
                    string str = language + "|" + temp.trans_result[0].dst;
                // Debug.LogError(str);
                wen_show.GetComponent<Text>().text = temp.trans_result[0].dst;
                print(str);
                //}
            }
        }
        return null;
    }

    private static string GetMD5WithString(string input)
    {
        if (input == null)
        {
            return null;
        }
        MD5 md5Hash = MD5.Create();
        //将输入字符串转换为字节数组并计算哈希数据  
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        //创建一个 Stringbuilder 来收集字节并创建字符串  
        StringBuilder sBuilder = new StringBuilder();
        //循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        //返回十六进制字符串  
        return sBuilder.ToString();
    }
}

public class Translation
{
    public string src { get; set; }
    public string dst { get; set; }
}

public enum Language
{
    //百度翻译API官网提供了多种语言,这里只列了几种
    zh,
    en,
    spa,
    fra,
    th,
    ara,
    ru,
    pt,
    de,
    el,
    vie,
    cht,
    yue,
}

public class TranslationResult
{
    错误码,翻译结果无法正常返回
    //public string Error_code { get; set; }
    //public string Error_msg { get; set; }
    public string from { get; set; }
    public string to { get; set; }
   // public string Query { get; set; }
    //翻译正确,返回的结果
    //这里是数组的原因是百度翻译支持多个单词或多段文本的翻译,在发送的字段q中用换行符(\n)分隔
    public Translation[] trans_result { get; set; }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Unity百度AI口,你需要进行以下步骤: 1. 注册百度AI开放平台账号并创建应用,获取AppID、API Key和Secret Key。 2. 下载百度AI SDK for Unity,并将其导入到Unity项目中。 3. 在Unity项目中创建一个脚本,并在其中编写调用百度AI口的代码。例如,你可以使用语音识别口,将用户的语音转换成文本。代码示例如下: ``` using Baidu.Aip.Speech; using UnityEngine; public class SpeechRecognition : MonoBehaviour { private const string APP_ID = "你的AppID"; private const string API_KEY = "你的API Key"; private const string SECRET_KEY = "你的Secret Key"; private readonly AudioClip _microphoneClip = Microphone.Start(null, true, 10, 16000); private SpeechRecognizer _speechRecognizer; private void Start() { _speechRecognizer = new SpeechRecognizer(API_KEY, SECRET_KEY); _speechRecognizer.Timeout = 60000; } private void Update() { // 等待录音结束 if (Microphone.IsRecording(null) && Microphone.GetPosition(null) > 0) { return; } // 停止录音 Microphone.End(null); // 调用语音识别口 var result = _speechRecognizer.Recognize(_microphoneClip.GetData(), "pcm", 16000); if (result != null && result.ErrorCode == 0) { Debug.Log(result.Result[0]); } } } ``` 4. 在Unity中添加麦克风权限,以允许应用访问麦克风。 5. 对于其他的百度AI口,你可以参考百度AI SDK for Unity中的示例代码,并根据具体需求进行修改。 以上就是在Unity百度AI口的基本步骤。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值