unity 接入百度API——AI作画

完整代码下载地址:https://download.csdn.net/download/weixin_43703390/89179785 打不开就是还在审核中…

账号注册创建模块:

1.打开百度智能云官网:[https://cloud.baidu.com/?from=console],在【产品】中找到【语言与知识】下的【AI作画】
请添加图片描述
2.打开界面后点击【立即使用】,然后创建应用,得到API Key和Secret Key
在这里插入图片描述
3.点击左侧【API在线调试】选择对应的版本
在这里插入图片描述
6.如果调试成功的画,就可在unity项目中开始使用了

代码模块

代码步骤1:首先根据API Key和Secret Key获取token

 private string API_KEY = "111111"; // 替换为你的API Key  
 private string SECRET_KEY = "2222222"; // 替换为你的Secret Key  
 public string m_Token = string.Empty;
 
 IEnumerator GetToken()
 {

     //获取token的api地址
     string _token_url = string.Format("https://aip.baidubce.com/oauth/2.0/token" + "?client_id={0}&client_secret={1}&grant_type=client_credentials"
         , API_KEY, SECRET_KEY);

     using (UnityWebRequest request = new UnityWebRequest(_token_url, "GET"))
     {
         request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
         yield return request.SendWebRequest();
         if (request.isDone)
         {
             string _msg = request.downloadHandler.text;
             TokenInfo _textback = JsonUtility.FromJson<TokenInfo>(_msg);
             m_Token = _textback.access_token;

         }
     }

 }
 /// <summary>
 /// 返回的token
 /// </summary>
 [System.Serializable]
 public class TokenInfo
 {
     public string access_token = string.Empty;
 }

代码步骤2:使用网络上传图片生成描述数据

TaskData taskData=new TaskData();
string url = $"https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token={m_Token}";

Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("text", "图片描述");
dic.Add("resolution", "1024*1024");//图片尺寸
dic.Add("style", "二次元");//图片风格
dic.Add("num", 1);//生成数量

using (UnityWebRequest www = UnityWebRequest.Post(url, "")) {
    www.SetRequestHeader("Content-Type", "application/json");
    byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dic));
    www.uploadHandler = new UploadHandlerRaw(bodyRaw);
    www.downloadHandler = new DownloadHandlerBuffer();
    yield return www.SendWebRequest();
    if (www.result == UnityWebRequest.Result.Success)
    {
        Debug.Log("结果1:"+ www.downloadHandler.text);
    }
    else
    {
        Debug.Log("结果2:" + www.error);
    }
}

代码步骤3:百度服务器图片生成之后,获取图片的信息

RootObject rootObject = new RootObject();
string urls = $"https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token={m_Token}";
using (UnityWebRequest www = UnityWebRequest.Post(urls, ""))
{
    www.SetRequestHeader("Content-Type", "application/json");
    Dictionary<string, object> dica = new Dictionary<string, object>();
    dica.Add("taskId", "返回的任务ID");

    byte[] bodyRaw = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dica));
    www.uploadHandler = new UploadHandlerRaw(bodyRaw);
    www.downloadHandler = new DownloadHandlerBuffer();

    yield return www.SendWebRequest();

    if (www.result == UnityWebRequest.Result.Success)
    {
        Debug.Log("结果2:" + www.downloadHandler.text);
    }
    else
    {
        Debug.Log("结果2:" + www.error);
    }
}

代码步骤4:根据返回信息中的网址下载图片 返回信息中的【status】0或1。"1"表示已生成完成,"0"表示任务排队中或正在处理.

using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(rootObject.data.img)) {

    yield return www.SendWebRequest();

    if (www.result == UnityWebRequest.Result.Success)
    {
        // 成功下载图片
        Texture2D texture = DownloadHandlerTexture.GetContent(www);
        if (texture != null)
        {
            // 获取成功
            Debug.log("获取成功");
        }
    }
    else
    {
        // 下载失败
        Debug.LogError("Failed to download image: " + www.error);
    }
}
要在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接口的基本步骤。希望对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值