unity 接入百度人工智能Demo
Unity 版本 2020.1.0a12LoadAudio// ========================================================// 描述:加载音乐// 作者:qinglong// 创建时间:2020-04-07 11:31:27// 版 本:1.0// ========================================...
Unity 版本 2020.1.0a12
demo 下载
LoadAudio
// ========================================================
// 描述:加载音乐
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using System;
using UnityEngine;
using UnityEngine.Networking;
public class LoadAudio : MonoBehaviour
{
public IEnumerator LoadMusic(string filepath,Action<AudioClip> callback=null)
{
filepath = "file://" + filepath;
var uwr = UnityWebRequestMultimedia.GetAudioClip(filepath, AudioType.MPEG);
((DownloadHandlerAudioClip)uwr.downloadHandler).compressed = false;
((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true;
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.LogError(uwr.error);
}
else
{
AudioClip clip = DownloadHandlerAudioClip.GetContent(uwr);
if (callback!=null)
{
callback(clip);
}
}
}
}
麦克风 MicphoneRecord
// ========================================================
// 描述:麦克风 MicphoneRecord
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class MicphoneRecord : MonoBehaviour
{
private int Frequency = 16000; //录音频率
private int MicSecond = 100; //录音时长10s
public Button Backbutton;
public GameObject mImage;
public Image[] images;
float mintime = 0;
bool isStart;
string device;
AudioClip audioClip;
void Start()
{
mImage.SetActive(false);
device = Microphone.devices[0];//获取设备麦克风
Backbutton.onClick.AddListener(()=> {
SceneManager.LoadScene(Configures.StartScence);
});
}
private void Update()
{
if (isStart)
{
mintime += Time.deltaTime;
}
showImage();
}
public void OnStartClick()
{
mintime = 0;
isStart = true;
audioClip = Microphone.Start(null, false, MicSecond, Frequency);
mImage.SetActive(true);
}
public void OnStopClick()
{
if (!Microphone.IsRecording(null))
return;
Microphone.End(null);
isStart = false;
mImage.SetActive(false);
audioClip = GetTransformAudioClip(audioClip, mintime);
SavWav.Save(Configures.AudioName, audioClip);
SceneManager.LoadScene(Configures.BaseScence);
}
/// <summary>
/// 音频剪辑
/// </summary>
/// <param name="srcAudioClip"></param>
/// <param name="_minSecond">最小时长</param>
/// <param name="_3D">是否是3D效果</param>
/// <param name="stream">True if clip is streamed, that is if the pcmreadercallback generates data on the fly.</param>
/// <returns></returns>
private AudioClip GetTransformAudioClip(AudioClip srcAudioClip, float _minSecond, bool _3D = false, bool stream = false)
{
int temp = Mathf.CeilToInt(_minSecond);
var samplesArr = new float[srcAudioClip.samples];
srcAudioClip.GetData(samplesArr, 0);
List<float> samples = new List<float>(samplesArr);
bool isLessMin = true;
if (Mathf.Abs(srcAudioClip.length) > temp)
{
isLessMin = false;
}
if (isLessMin)
{
return srcAudioClip;
}
for (int i = samples.Count - 1; i > 0; i--)
{
if (samples[i] != 0)
{
break;
}
samples.RemoveRange(i, 1);
}
var clip = AudioClip.Create("TempClip", samples.Count, srcAudioClip.channels, srcAudioClip.frequency, _3D, stream);
Debug.Log("clip.length " + clip.length);
clip.SetData(samples.ToArray(), 0);
return clip;
}
//每一振处理那一帧接收的音频文件
float GetMaxVolume()
{
float maxVolume = 0f;
//剪切音频
float[] volumeData = new float[128];
int offset = Microphone.GetPosition(device) - 128 + 1;
if (offset < 0)
{
return 0;
}
audioClip.GetData(volumeData, offset);
for (int i = 0; i < 128; i++)
{
float tempMax = volumeData[i];//修改音量的敏感值
if (maxVolume < tempMax)
{
maxVolume = tempMax;
}
}
return maxVolume;
}
/// <summary>
/// 展示音频的信息
/// </summary>
void showImage()
{
float value = ((int)(GetMaxVolume() * 100)) / 10.0f;
for (int i = 0; i < images.Length; i++)
{
if (i <= value)
{
images[images.Length - i - 1].gameObject.SetActive(true);
}
else
{
images[images.Length - i - 1].gameObject.SetActive(false);
}
}
}
}
保存音频SavWav
// ========================================================
// 描述:保存音频SavWav
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System;
using System.IO;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
public static class SavWav
{
const int HEADER_SIZE = 44;
public static bool Save(string filename, AudioClip clip)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string path = Configures.SpeechAudios_Andriod;
#elif UNITY_EDITOR
string path = Configures.SpeechAudios_Unity;
#endif
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var filepath = path + filename;
Debug.Log("filepath路径 "+ filepath);
var fileStream = CreateEmpty(filepath);
ConvertAndWrite(fileStream, clip);
WriteHeader(fileStream, clip);
fileStream.Flush();
fileStream.Close();
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
return true; // TODO: return false if there's a failure saving the file
}
static FileStream CreateEmpty(string filepath)
{
var fileStream = new FileStream(filepath, FileMode.Create);
byte emptyByte = new byte();
for (int i = 0; i < HEADER_SIZE; i++) //preparing the header
{
fileStream.WriteByte(emptyByte);
}
return fileStream;
}
static void ConvertAndWrite(FileStream fileStream, AudioClip clip)
{
var samples = new float[clip.samples];
clip.GetData(samples, 0);
Int16[] intData = new Int16[samples.Length];
Byte[] bytesData = new Byte[samples.Length * 2];
int rescaleFactor = 32767; //to convert float to Int16
for (int i = 0; i < samples.Length; i++)
{
intData[i] = (short)(samples[i] * rescaleFactor);
Byte[] byteArr = new Byte[2];
byteArr = BitConverter.GetBytes(intData[i]);
byteArr.CopyTo(bytesData, i * 2);
}
fileStream.Write(bytesData, 0, bytesData.Length);
}
static void WriteHeader(FileStream fileStream, AudioClip clip)
{
var hz = clip.frequency;
var channels = clip.channels;
var samples = clip.samples;
fileStream.Seek(0, SeekOrigin.Begin);
Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
fileStream.Write(riff, 0, 4);
Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
fileStream.Write(chunkSize, 0, 4);
Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
fileStream.Write(wave, 0, 4);
Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
fileStream.Write(fmt, 0, 4);
Byte[] subChunk1 = BitConverter.GetBytes(16);
fileStream.Write(subChunk1, 0, 4);
//UInt16 two = 2;
UInt16 one = 1;
Byte[] audioFormat = BitConverter.GetBytes(one);
fileStream.Write(audioFormat, 0, 2);
Byte[] numChannels = BitConverter.GetBytes(channels);
fileStream.Write(numChannels, 0, 2);
Byte[] sampleRate = BitConverter.GetBytes(hz);
fileStream.Write(sampleRate, 0, 4);
Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
fileStream.Write(byteRate, 0, 4);
UInt16 blockAlign = (ushort)(channels * 2);
fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);
UInt16 bps = 16;
Byte[] bitsPerSample = BitConverter.GetBytes(bps);
fileStream.Write(bitsPerSample, 0, 2);
Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
fileStream.Write(datastring, 0, 4);
Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
fileStream.Write(subChunk2, 0, 4);
}
}
人体检测Base 类
// ========================================================
// 描述:人体检测Base 类
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.BodyAnalysis;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BodyBase : RecognitionBase
{
// 设置APPID/AK/SK
//string APP_ID = "19132779";
protected string API_KEY = "3EWZpwanq1yzHiSZ4p5xUUaq";
protected string SECRET_KEY = "lAglQG7FQ142v1sCKAV5SlCwGC09D3sL";
protected Body client;
private void Awake()
{
client = new Body(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
}
人体检测 BodyAnalysisBody
// ========================================================
// 描述:人体检测
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class BodyAnalysisBody :BodyBase
{
void Start()
{
BodyAttrDemo(()=> {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
public void BodyAttrDemo(Action callback)
{
try
{
// 调用人体检测与属性识别,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.BodyAttr(GetImage());
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
//{"type", "gender"}
};
// 带参数调用人体检测与属性识别
var result = client.BodyAttr(GetImage(), options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
人体检测json BodyAnalysisBodyJson
// ========================================================
// 描述:人体检测json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class BodyAnalysisBodyJson
{
static Person player;
static string path;
public static string JsonToFrom()
{
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
string rst = "共识别出"+player.person_num+ "个人\n.";
for (int i = 0; i < player.person_num; i++)
{
rst += "第" + (i + 1) + "个人";
rst += player.person_info[i].attributes.occlusion.name + ". \n"; //是否有遮挡
rst += player.person_info[i].attributes.age.name + ". \n"; //年龄
rst += player.person_info[i].attributes.gender.name + ". \n"; //性别
rst +="身体朝向"+ player.person_info[i].attributes.orientation.name + ". \n"; //朝向
//头部
rst += player.person_info[i].attributes.headwear.name + ". \n"; //是否戴帽子
rst += player.person_info[i].attributes.face_mask.name + ". \n"; //是否戴口罩
rst += player.person_info[i].attributes.glasses.name + ". \n"; // //是否戴眼镜
//上半身
rst +="上身身着\n" +player.person_info[i].attributes.upper_color.name + ","; //颜色
rst +=player.person_info[i].attributes.upper_wear_texture.name + ","; //上身服饰纹理,
rst += player.person_info[i].attributes.upper_wear.name + ","; //上身服饰
rst += player.person_info[i].attributes.upper_wear_fg.name + ". \n"; //上身衣服样式
//下半身
rst += "下身身着\n" + player.person_info[i].attributes.lower_color.name + "\n "; //下身衣着颜色
rst += player.person_info[i].attributes.lower_wear.name + ". \n"; //下身衣着样式
rst += player.person_info[i].attributes.bag.name + ". \n"; //是否带包
rst += player.person_info[i].attributes.umbrella.name + ". \n"; //是否撑伞
rst += player.person_info[i].attributes.carrying_item.name + ". \n"; //是否有手提物
rst += player.person_info[i].attributes.cellphone.name + ". \n"; //是否玩手机
rst += player.person_info[i].attributes.smoke.name + ". \n"; //是否吸烟
rst += player.person_info[i].attributes.vehicle.name + ". \n"; //是否有交通工具
rst += player.person_info[i].attributes.is_human.name + ". \n"; //是否是正常人体
}
Debug.Log(rst);
return rst;
}
[Serializable]
public class orientation
{
public double score;
public string name;
public orientation(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class is_human
{
public double score;
public string name;
public is_human(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class headwear
{
public double score;
public string name;
public headwear(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class upper_wear_texture
{
public double score;
public string name;
public upper_wear_texture(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class carrying_item
{
public double score;
public string name;
public carrying_item(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class face_mask
{
public double score;
public string name;
public face_mask(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class lower_wear
{
public double score;
public string name;
public lower_wear(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class vehicle
{
public double score;
public string name;
public vehicle(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class upper_wear_fg
{
public double score;
public string name;
public upper_wear_fg(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class lower_color
{
public double score;
public string name;
public lower_color(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class umbrella
{
public double score;
public string name;
public umbrella(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class upper_cut
{
public double score;
public string name;
public upper_cut(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class lower_cut
{
public double score;
public string name;
public lower_cut(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class upper_wear
{
public double score;
public string name;
public upper_wear(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class cellphone
{
public double score;
public string name;
public cellphone(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class gender
{
public double score;
public string name;
public gender(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class age
{
public double score;
public string name;
public age(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class bag
{
public double score;
public string name;
public bag(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class smoke
{
public double score;
public string name;
public smoke(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class upper_color
{
public double score;
public string name;
public upper_color(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class occlusion
{
public double score;
public string name;
public occlusion(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class glasses
{
public double score;
public string name;
public glasses(double _score, string _name)
{
score = _score;
name = _name;
}
}
[Serializable]
public class location
{
public double height;
public double width;
public double top;
public double score;
public double left;
public location(double _height, double _width, double _top, double _score, double _left)
{
height = _height;
width = _width;
top = _top;
score = _score;
left = _left;
}
}
[Serializable]
public class attributes
{
public orientation orientation;
public is_human is_human;
public headwear headwear;
public upper_wear_texture upper_wear_texture;
public carrying_item carrying_item;
public face_mask face_mask;
public lower_wear lower_wear;
public vehicle vehicle;
public upper_wear_fg upper_wear_fg;
public lower_color lower_color;
public umbrella umbrella;
public upper_cut upper_cut;
public lower_cut lower_cut;
public upper_wear upper_wear;
public cellphone cellphone;
public gender gender;
public age age;
public bag bag;
public smoke smoke;
public upper_color upper_color;
public occlusion occlusion;
public glasses glasses;
public attributes(orientation _orientation, is_human _is_human, headwear _headwear,
upper_wear_texture _upper_wear_texture, carrying_item _carrying_item, face_mask _face_mask,
lower_wear _lower_wear, vehicle _vehicle, upper_wear_fg _upper_wear_fg,
lower_color _lower_color, umbrella _umbrella, upper_cut _upper_cut,
lower_cut _lower_cut, upper_wear _upper_wear, cellphone _cellphone,
gender _gender, age _age, bag _bag, smoke _smoke,
upper_color _upper_color, occlusion _occlusion, glasses _glasses )
{
orientation = _orientation;
is_human = _is_human;
headwear = _headwear;
upper_wear_texture = _upper_wear_texture;
carrying_item = _carrying_item;
face_mask = _face_mask;
lower_wear = _lower_wear;
vehicle = _vehicle;
upper_wear_fg = _upper_wear_fg;
lower_color = _lower_color;
umbrella = _umbrella;
upper_cut = _upper_cut;
lower_cut = _lower_cut;
upper_wear = _upper_wear;
cellphone = _cellphone;
gender = _gender;
age = _age;
bag = _bag;
smoke = _smoke;
upper_color = _upper_color;
occlusion = _occlusion;
glasses = _glasses;
}
}
[Serializable]
public class person_info
{
public attributes attributes;
public location location;
public person_info(attributes _attributes, location _location)
{
attributes = _attributes;
location = _location;
}
}
[Serializable]
public class Person
{
public int person_num;
public person_info[] person_info;
public Person(int _person_num, person_info[] _person_info)
{
person_num = _person_num;
person_info = _person_info;
}
}
}
手势识别 HandRecognition
// ========================================================
// 描述:手势识别
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class HandRecognition : BodyBase
{
void Start()
{
GestureDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
public void GestureDemo(Action callback=null)
{
try
{
// 调用手势识别,可能会抛出网络等异常,请使用try/catch捕获
var result = client.Gesture(GetImage());
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log(e);
}
if (callback != null)
{
callback();
}
}
}
手势识别 json
// ========================================================
// 描述:手势识别 json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class HandRecognitionJson
{
static Person player;
static string path;
public static string JsonToFrom()
{
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
string str = "发现" + player.result_num + "种手势\n";
for (int i = 0; i < player.result_num; i++)
{
str += "第" + (i + 1) + "个手势是" + getHand(player.result[i].classname)+"\n";
}
return str;
}
static string getHand(string name) {
Debug.Log(name);
switch (name)
{
case "One":
return "数字1 或 食指";
case "Two":
return "数字2";
case "Three":
return "数字3";
case "Four":
return "数字4";
case "Five":
return "数字5 或 掌心向前";
case "Six":
return "数字6";
case "Seven":
return "数字7";
case "Eight":
return "数字8";
case "Nine":
return "数字9";
case "Rock":
return "Rock";
case "Insult":
return "竖中指";
case "Fist":
return "拳头";
case "OK":
return "OK";
case "Prayer":
return "祈祷";
case "Congratulation":
return "作揖";
case "Honour":
return "作别";
case "Heart_single":
return "单手比心";
case "Thumb_up":
return "点赞";
case "Thumb_down":
return "Diss";
case "ILY":
return "Rock";
case "Palm_up":
return "掌心向上";
case "Heart_1":
case "Heart_2":
case "Heart_3":
return "双手比心";
default:
return name+"没有相应的匹配手势";
}
}
[Serializable]
public class result
{
public long probability;
public float top;
public float height;
public string classname;
public float width;
public float left;
public result(long _probability, float _top, float _height, string _classname, float _width, float _left)
{
probability = _probability;
top = _top;
height = _height;
classname = _classname;
width = _width;
left = _left;
}
}
[Serializable]
public class Person
{
public long log_id;
public int result_num;
public result[] result;
public Person(long _log_id,int _result_num, result[] _result)
{
log_id = _log_id;
result_num = _result_num;
result = _result;
}
}
}
文字识别 CharacterRecognition
// ========================================================
// 描述:文字识别
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections.Generic;
using UnityEngine;
using Baidu.Aip.Ocr;
using System;
using UnityEngine.SceneManagement;
public class CharacterRecognition : RecognitionBase
{
// 设置APPID/AK/SK
//string APP_ID = "18431106";
string API_KEY = "AsS6GVye2ahSoToKTGDSg2qg";
string SECRET_KEY = "VYYx2oxfdQDGMIIIEnlU44NIGOqP0ArU";
Ocr client;
void Awake()
{
client = new Ocr(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
private void Start()
{
GeneralBasicDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
public void GeneralBasicDemo(Action callback)
{
try
{
// 如果有可选参数
var options = new Dictionary<string, object>{
{"language_type", "CHN_ENG"},
{"detect_direction", "true"},
{"detect_language", "true"},
{"probability", "true"},
};
// 带参数调用通用文字识别, 图片参数为本地图片
var result = client.GeneralBasic(GetImage(), options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
文字识别json
// ========================================================
// 描述:文字识别json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class CharResulttoJson
{
static Person player;
static string path;
public static string JsonToFrom()
{
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
string rst = null;
for (int i = 0; i < player.words_result.Length; i++)
{
rst += player.words_result[i].words + ". \n";
}
Debug.Log(rst);
return rst;
}
[Serializable]
public class words_result
{
public string words;
public probability probability;
public words_result( string _words, probability _probability)
{
words = _words;
probability = _probability;
}
}
[Serializable]
public class probability
{
public double variance;
public double average;
public double min;
public probability(double _variance, double _average, double _min)
{
variance = _variance;
average = _average;
min = _min;
}
}
[Serializable]
public class Person
{
public long log_id;
public int direction;
public int words_result_num;
public words_result[] words_result;
public Person(long _log_id,int _direction, int _words_result_num, words_result[] _words_result)
{
log_id = _log_id;
direction = _direction;
words_result_num = _words_result_num;
words_result = _words_result;
}
}
}
人脸检测 FaceDetect
// ========================================================
// 描述:人脸检测 FaceDetect
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections.Generic;
using UnityEngine;
using Baidu.Aip.Face;
using System;
using UnityEngine.SceneManagement;
/// <summary>
/// 人脸检测
/// </summary>
public class FaceDetect : RecognitionBase
{
// 设置APPID/AK/SK
//string APP_ID = "18452723";
string API_KEY = "SrxcWap215lhS6ZCXo3K9rp4";
string SECRET_KEY = "2cNnWUbrIpC96had6yGmIQT1TVyC0tdz";
Face client;
void Awake()
{
client = new Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
private void Start()
{
DetectDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
public void DetectDemo(Action callback)
{
var imageType = "BASE64";
try
{
// 调用人脸检测,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.Detect(image, imageType);
// Debug.Log(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"face_field","age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,eye_status,emotion,face_type"},
{"max_face_num", 2},
{"face_type", "LIVE"},
{"liveness_control", "NONE"}
};
// 带参数调用人脸检测
var result = client.Detect(GetImage("string"), imageType, options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
人脸检测json
// ========================================================
// 描述:人脸检测json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class FaceResultJson
{
static Person player;
public static string JsonToFrom()
{
string path;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return resultStr();
}
static string resultStr() {
if (player.error_code!=0)
{
return player.error_code+ " 错误 " + player.error_msg;
}
string s = "人脸数量 :"+ player.result.face_num+"人" + ". \n";
for (int i = 0; i < player.result.face_list.Length; i++)
{
face_list FL = player.result.face_list[i];
//s += "人脸图片的唯一标识" + FL.face_token + "\n"
if (player.result.face_num > 1) {
s += "第" + (i + 1) + "个人. \n ";
}
// s += "人脸在相机中的位置:\n"
// + "距左边界:" + FL.location.left + ". \n"
// + "距上边界:" + FL.location.top + ". \n"
// + "宽:" + FL.location.width + ". \n"
// + "高:" + FL.location.height + ". \n"
// + "旋转:" + FL.location.rotation + ". \n"
//
// // + "人脸置信度" + FL.face_probability + "\n"
//
// + "人脸旋转角度:\n"
// + "三维旋转之左右旋转角:" + FL.angle.yaw + ". \n"
// + "三维旋转之俯仰旋转角:" + FL.angle.pitch + ". \n"
// + "平面旋转角度:" + FL.angle.roll + ". \n"
s+= "年龄:" + FL.age + ". \n"
+ "漂亮程度:" + FL.beauty + ". \n"
+ "表情:" + expressiontype(FL.expression.type) + ". \n"
//+ "表情可信度" + FL.expression.probability + ". \n"
+ "脸型:" + face_Shapetype(FL.face_shape.type) + ". \n"
//+ "脸型可信度" + FL.face_Shape.probability + ". \n"
+ "性别:" + gendertype(FL.gender.type) + ". \n"
//+ "性别可信度" + FL.gender.probability +". \n"
+ "眼镜类型:" + glassestype(FL.glasses.type) + ". \n"
//+ "眼镜类型可信度" + FL.glasses.probability + ". \n"
//+ "左眼打开程度:" + FL.eye_status.left_eye + ". \n"
// + "右眼打开程度:" + FL.eye_status.right_eye + ". \n"
+ "情绪:" + emotiontype(FL.emotion.type) + ". \n"
// + "情绪可信度" + FL.emotion.probability + ". \n"
+ "人种:" + raceype(FL.race.type) + ". \n"
//+ "人种识别可信度" + FL.race.probability + ". \n"
+ "人脸类型:" + faceType(FL.face_type.type) + ". \n"
// + "人脸类型可信度" +FL.face_Type.probability + ". \n"
// + "人脸左眼遮挡率:" + FL.quality.occlusion.left_eye + ". \n"
// + "人脸右眼遮挡率:" + FL.quality.occlusion.right_eye + ". \n"
// + "人脸鼻子遮挡率:" + FL.quality.occlusion.nose + ". \n"
// + "人脸嘴巴遮挡率:" + FL.quality.occlusion.mouth + ". \n"
// + "左脸遮挡率:" + FL.quality.occlusion.left_cheek + ". \n"
// + "右脸遮挡率:" + FL.quality.occlusion.right_cheek + ". \n"
// + "下巴遮挡率:" + FL.quality.occlusion.chin_contour + ". \n"
//
// + "人脸模糊程度:" + FL.quality.blur + ". \n"
// + "人脸区域光照程度:" + FL.quality.illumination + ". \n"
// + "人脸是否完整在相机里:" + FL.quality.completeness
;
}
/// <summary>
/// 表情类型
/// </summary>
string expressiontype( string _type) {
switch (_type)
{
case "none":
return "不笑";
case "smile":
return "微笑";
case "laugh":
return "大笑";
default:
return _type;
}
}
string face_Shapetype(string _type)
{
Debug.Log("脸型" + _type);
switch (_type)
{
case "square":
return "正方形";
case "triangle":
return "三角形";
case "oval":
return "椭圆";
case "heart":
return "心形";
case "round":
return "圆形";
default:
return _type;
}
}
string gendertype(string _type)
{
switch (_type)
{
case "male":
return "男性";
case "female":
return "女性";
default:
return _type;
}
}
string glassestype(string _type) {
switch (_type)
{
case "none":
return "没带眼镜";
case "common":
return "普通眼镜";
case "sun":
return "墨镜";
default:
return _type;
}
}
string emotiontype(string _type)
{
switch (_type)
{
case "angry":
return "愤怒";
case "disgust":
return "厌恶";
case "fear":
return "恐惧";
case "happy":
return "高兴";
case "sad":
return "伤心";
case "surprise":
return "惊讶";
case "neutral":
return "无情绪";
default:
return _type;
}
}
string raceype(string _type)
{
switch (_type)
{
case "yellow":
return "黄种人";
case "white":
return "白种人";
case "black":
return "黑种人";
case "arabs":
return "阿拉伯人";
default:
return _type;
}
}
string faceType(string _type)
{
Debug.Log("人脸类型"+ _type);
switch (_type)
{
case "human":
return "真实人脸";
case "cartoon":
return "卡通人脸";
default:
return _type;
}
}
return s;
}
[Serializable]
public class Person
{
public int error_code;
public string error_msg;
public long log_id;
public long timestamp;
public int cached;
public result result;
public Person(int _error_code, string _error_msg, long _log_id, long _timestamp, int _cached, result _result)
{
error_code = _error_code;
error_msg = _error_msg;
log_id = _log_id;
timestamp = _timestamp;
cached = _cached;
result = _result;
}
}
[Serializable]
public class result
{
public int face_num;
public face_list[] face_list;
public result(int _face_num, face_list[] _face_list)
{
face_num = _face_num;
face_list = _face_list;
}
}
[Serializable]
public class face_list
{
public string face_token;
public location location;
public int face_probability;
public angle angle;
public liveness liveness;
public int age;
public double beauty;
public expression expression;
public face_shape face_shape;
public gender gender;
public glasses glasses;
public race race;
public quality quality;
public eye_status eye_status;
public emotion emotion;
public face_type face_type;
public face_list(string _face_token, location _location, int _face_probability, angle _angle, liveness _liveness,
int _age, double _beauty, expression _expression, face_shape _face_Shape, gender _gender, glasses _glasses, race _race,
quality _quality, eye_status _eye_status, emotion _emotion, face_type _face_type)
{
face_token = _face_token;
location = _location;
face_probability = _face_probability;
angle = _angle;
liveness = _liveness;
age = _age;
beauty = _beauty;
expression = _expression;
face_shape = _face_Shape;
gender = _gender;
glasses = _glasses;
race = _race;
quality = _quality;
eye_status = _eye_status;
emotion = _emotion;
face_type = _face_type;
}
}
[Serializable]
public class location
{
public double left;
public double top;
public double width;
public double height;
public double rotation;
public location(double _left , double _top, double _width, double _height, double _rotation)
{
left = _left;
top = _top;
width = _width;
height = _height;
rotation = _rotation;
}
}
[Serializable]
public class angle
{
public double yaw;
public double pitch;
public double roll;
public angle(double _yaw, double _pitch, double _roll)
{
yaw = _yaw;
pitch = _pitch;
roll = _roll;
}
}
[Serializable]
public class liveness
{
public double livemapscore;
public liveness(double _livemapscore)
{
livemapscore = _livemapscore;
}
}
[Serializable]
public class expression
{
public string type;
public double probability;
public expression(string _type ,double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class face_shape
{
public string type;
public double probability;
public face_shape(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class gender
{
public string type;
public double probability;
public gender(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class glasses
{
public string type;
public double probability;
public glasses(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class race
{
public string type;
public double probability;
public race(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class quality
{
public occlusion occlusion;
public double blur;
public double illumination;
public double completeness;
public quality(occlusion _occlusion, double _blur, double _illumination, double _completeness)
{
occlusion = _occlusion;
blur = _blur;
illumination = _illumination;
completeness = _completeness;
}
}
[Serializable]
public class occlusion
{
public double left_eye;
public double right_eye;
public double nose;
public double mouth;
public double left_cheek;
public double right_cheek;
public double chin_contour;
public occlusion(double _left_eye, double _right_eye, double _nose, double _mouth, double _left_cheek, double _right_cheek, double _chin_contour)
{
left_eye = _left_eye;
right_eye = _right_eye;
nose = _nose;
mouth = _mouth;
left_cheek = _left_cheek;
right_cheek = _right_cheek;
chin_contour = _chin_contour;
}
}
[Serializable]
public class eye_status
{
public double left_eye;
public double right_eye;
public eye_status(double _left_eye, double _right_eye)
{
left_eye = _left_eye;
right_eye = _right_eye;
}
}
[Serializable]
public class emotion
{
public string type;
public double probability;
public emotion(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
[Serializable]
public class face_type
{
public string type;
public double probability;
public face_type(string _type, double _probability)
{
type = _type;
probability = _probability;
}
}
}
添加人脸 FaceAddUI
// ========================================================
// 描述:添加人脸
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.IO;
public class FaceAddUI : MonoBehaviour
{
GameObject UserAddPanel;
RawImage mRawImage;
InputField UserID;
InputField UserInfo;
Button OKbutton;
Button Backbutton;
FaceSearchTool MFaceSearchTool;
GameObject ShowResult;
void Start()
{
MFaceSearchTool = GetComponent<FaceSearchTool>();
UserAddPanel = GameObject.Find("Canvas").transform.Find("UserAddPanel").gameObject;
UserAddPanel.SetActive(true);
mRawImage = UserAddPanel.transform.Find("RawImage").GetComponent<RawImage>();
UserID = UserAddPanel.transform.Find("UserID").GetComponent<InputField>();
UserInfo = UserAddPanel.transform.Find("UserInfo").GetComponent<InputField>();
OKbutton = UserAddPanel.transform.Find("OK").GetComponent<Button>();
Backbutton = UserAddPanel.transform.Find("Back").GetComponent<Button>();
ShowResult = UserAddPanel.transform.Find("ShowResult").gameObject;
ShowResult.SetActive(false);
loadImage();
OKbutton.onClick.AddListener(() => {
MFaceSearchTool.UserAddDemo(UserID.text, UserInfo.text, "MyFace", (result) => {
ShowResult.SetActive(true);
});
});
Backbutton.onClick.AddListener(() => {
SceneManager.LoadScene(Configures.StartScence);
});
}
//动态加载图片
void loadImage()
{
#if UNITY_ANDROID && !UNITY_EDITOR
string path = Configures.PhotoPath_Andriod;
#elif UNITY_EDITOR
string path = Configures.PhotoPath_Unity;
#endif
//创建文件读取流
FileStream fileStream = new FileStream(path + Configures.pictureName, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
//创建文件长度缓冲区
byte[] bytes = new byte[fileStream.Length];
//读取文件
fileStream.Read(bytes, 0, (int)fileStream.Length);
//释放文件读取流
fileStream.Close();
fileStream.Dispose();
fileStream = null;
//创建Texture
Texture2D texture = new Texture2D(Screen.width, Screen.height);
texture.LoadImage(bytes);
mRawImage.texture = texture;
}
}
人脸识别base FaceSearchBase
// ========================================================
// 描述: 人脸识别base
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FaceSearchBase : RecognitionBase
{
protected string APP_ID = "18452723";
protected string API_KEY = "SrxcWap215lhS6ZCXo3K9rp4";
protected string SECRET_KEY = "2cNnWUbrIpC96had6yGmIQT1TVyC0tdz";
protected string groupIdList= "MyFace";
protected string user_id = "QL";
protected Face client;
void Awake()
{
client = new Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
}
人脸识别 1 对多 mFaceSearchOneVSMulti
// ========================================================
// 描述:人脸识别 1 对多
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class mFaceSearchOneVSMulti : FaceSearchBase
{
private void Start()
{
SearchDemo(groupIdList, user_id, () =>
{
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 人脸搜索 1:N 识别
/// </summary>
/// <param name="groupIdList">从指定的group中进行查找 用逗号分隔,上限20个</param>
/// <param name="callback"></param>
public void SearchDemo(string groupIdList,string user_id=null, Action callback =null)
{
var imageType = "BASE64";
try
{
// 调用人脸搜索,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.Search(image, imageType, groupIdList);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"max_face_num", 3},
{"match_threshold", 70},
{"quality_control", "NORMAL"},
{"liveness_control", "NONE"},
{ "user_id", user_id},
{"max_user_num", 3}
};
// 带参数调用人脸搜索
var result = client.Search(GetImage("string"), imageType, groupIdList, options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
人脸识别1对多json
// ========================================================
// 描述:人脸识别1对多json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class FaceSearchOneVSMultiJson
{
static Person player;
public static string JsonToFrom()
{
string path;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return resultStr();
}
public static string resultStr() {
string str = "";
for (int i = 0; i < player.result.user_list.Length; i++)
{
str += "当前人脸在数据库中的位置 " + player.result.user_list[i].group_id + " 分组,\n"
+ "用户名是 " + player.result.user_list[i].user_id + ",\n"
+ "注册用户时携带的用户信息是 " + player.result.user_list[i].user_info + ",\n"
+ "用户的匹配可信度 " + player.result.user_list[i].score.ToString("0.00");
}
return str;
}
[Serializable]
public class Person
{
public int error_code;
public string error_msg;
public long log_id;
public long timestamp;
public result result;
public Person(int _error_code, string _error_msg, long _log_id, long _timestamp, result _result)
{
error_code = _error_code;
error_msg = _error_msg;
log_id = _log_id;
timestamp = _timestamp;
result = _result;
}
}
[Serializable]
public class result
{
public string face_token;
public user_list[] user_list;
public result(string _face_token, user_list[] _user_list)
{
face_token = _face_token;
user_list = _user_list;
}
}
[Serializable]
public class user_list
{
public string group_id;
public string user_id;
public string user_info ;
public double score;
public user_list(string _group_id, string _user_id, string _user_info, double _score)
{
group_id = _group_id;
user_id = _user_id;
user_info = _user_info;
score = _score;
}
}
}
人脸识别 工具类FaceSearchTool
// ========================================================
// 描述:人脸识别 工具类
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class FaceSearchTool : RecognitionBase
{
// 设置APPID/AK/SK
protected string APP_ID = "18452723";
protected string API_KEY = "SrxcWap215lhS6ZCXo3K9rp4";
protected string SECRET_KEY = "2cNnWUbrIpC96had6yGmIQT1TVyC0tdz";
protected Face client;
void Awake()
{
client = new Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
//UserAddDemo("MyFace","YQ","小强强,强强科技");
}
protected string onlyGetImage()
{
//读取
FileInfo file = new FileInfo(Application.streamingAssetsPath + "/Photo" + "/yq.png");
var stream = file.OpenRead();
byte[] buffer = new byte[file.Length];
//读取图片字节流
stream.Read(buffer, 0, Convert.ToInt32(file.Length));
//base64字符串
string image = Convert.ToBase64String(buffer);
return image;
}
/// <summary>
/// 人脸注册
/// </summary>
/// <param name="callback"></param>
public void UserAddDemo( string userId,string user_info, string groupId , Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
var imageType = "BASE64";
Debug.Log("userId" + userId + "\nuser_info" + user_info + "\ngroupId" + groupId);
try
{
// 调用人脸注册,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.UserAdd(image, imageType, groupId, userId);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"user_info", user_info},
{"quality_control", "NORMAL"},
{"liveness_control", "NONE"},
{"action_type", "APPEND"}//向当前userid 下追加图片
};
// 带参数调用人脸注册
var result = client.UserAdd(GetImage(""), imageType, groupId, userId, options);
Debug.Log(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 人脸更新
/// </summary>
/// <param name="callback"></param>
public void UserUpdateDemo(string groupId, string userId, string user_info, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
var imageType = "BASE64";
try
{
// 调用人脸更新,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.UserUpdate(image, imageType, groupId, userId);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"user_info", user_info},
{"quality_control", "NORMAL"},
{"liveness_control", "LOW"},
{"action_type", "REPLACE"}
};
// 带参数调用人脸更新
var result = client.UserUpdate(GetImage(""), imageType, groupId, userId, options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 人脸删除
/// </summary>
/// <param name="callback"></param>
public void FaceDeleteDemo( string groupId, string userId, string faceToken, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用人脸删除,可能会抛出网络等异常,请使用try/catch捕获
var result = client.FaceDelete(userId, groupId, faceToken);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 用户信息查询
/// </summary>
public void UserGetDemo( string groupId, string userId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用用户信息查询,可能会抛出网络等异常,请使用try/catch捕获
var result = client.UserGet(userId, groupId);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 获取用户人脸列表
/// </summary>
public void FaceGetlistDemo( string groupId, string userId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用获取用户人脸列表,可能会抛出网络等异常,请使用try/catch捕获
var result = client.FaceGetlist(userId, groupId);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 用于查询指定用户组中的用户列表。
/// </summary>
public void GroupGetusersDemo(string groupId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
// 调用获取用户列表,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.GroupGetusers(groupId);
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"start", 0},
{"length", 50}
};
// 带参数调用获取用户列表
var result = client.GroupGetusers(groupId, options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 复制用户
/// </summary>
public void UserCopyDemo(string userId,string src_group_id ,string dst_group_id, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
// 调用复制用户,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.UserCopy(userId);
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"src_group_id",src_group_id},
{"dst_group_id", dst_group_id}
};
// 带参数调用复制用户
var result = client.UserCopy(userId, options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 删除用户
/// </summary>
public void UserDeleteDemo(string groupId, string userId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用删除用户,可能会抛出网络等异常,请使用try/catch捕获
var result = client.UserDelete(groupId, userId);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 创建用户组
/// </summary>
public void GroupAddDemo(string groupId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用创建用户组,可能会抛出网络等异常,请使用try/catch捕获
var result = client.GroupAdd(groupId);
Debug.Log(result);
// WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 删除用户组
/// </summary>
public void GroupDeleteDemo(string groupId, Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
try
{
// 调用删除用户组,可能会抛出网络等异常,请使用try/catch捕获
var result = client.GroupDelete(groupId);
Debug.Log(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 组列表查询
/// </summary>
public void GroupGetlistDemo(Action<Newtonsoft.Json.Linq.JObject> callback = null)
{
// 调用组列表查询,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.GroupGetlist();
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"start", 0},
{"length", 50}
};
// 带参数调用组列表查询
var result = client.GroupGetlist(options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback(result);
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
}
活体检测LivingTesting
// ========================================================
// 描述:活体检测
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LivingTesting : FaceSearchBase
{
private void Start()
{
LivingTestingDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 仅供 人脸检测 和人脸对比使用
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public string ReadImg(string img)
{
return Convert.ToBase64String(File.ReadAllBytes(img));
}
/// <summary>
/// 在线活体检测
/// </summary>
public void LivingTestingDemo(Action callback = null)
{
try
{
var faces = new JArray
{
new JObject
{
{"image", GetImage("string")},
{"image_type", "BASE64"},
{"face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype"},
},
new JObject
{
{"image", GetImage("string")},
{"image_type", "BASE64"}
}
};
var result = client.Faceverify(faces);
Console.WriteLine(result);
WriteResults(result);
if (callback != null) callback();
}
catch (Exception e)
{
WriteExceptions(e.ToString());
throw;
}
}
}
人脸对比mCompare
// ========================================================
// 描述:人脸对比mCompare
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using UnityEngine.SceneManagement;
using UnityEngine;
public class mCompare : FaceSearchBase
{
private void Start()
{
Comparedemo(()=> {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 人脸对比
/// </summary>
public void Comparedemo( Action callback = null)
{
try
{
var faces = new JArray
{
new JObject
{
{"image", GetImage("string","")[0]},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
},
new JObject
{
{"image",GetImage("string","")[1]},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
}
};
var result = client.Match(faces);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log(e);
}
if (callback != null) {
callback();
}
}
}
人脸对比 json
// ========================================================
// 描述:人脸对比 json
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class mCompareJson
{
static Person player;
public static string JsonToFrom()
{
string path;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return resultStr();
}
public static string resultStr() {
string str = "两张图片的相似度是 ";
str += player.result.score;
//str += player.result.face_list[0].face_token+"\n";
//str += player.result.face_list[0].face_token+"\n";
return str;
}
[Serializable]
public class Person
{
public int error_code;
public string error_msg;
public long log_id;
public long timestamp;
public float cached;
public result result;
public Person(int _error_code, string _error_msg, long _log_id, long _timestamp, float _cached, result _result)
{
error_code = _error_code;
error_msg = _error_msg;
log_id = _log_id;
timestamp = _timestamp;
cached = _cached;
result = _result;
}
}
[Serializable]
public class result
{
public int score;
public face_list[] face_list;
public result(int _score, face_list[] _face_list)
{
score = _score;
face_list = _face_list;
}
}
[Serializable]
public class face_list
{
public string face_token;
public face_list(string _face_token)
{
face_token = _face_token;
}
}
}
人脸识别mMultiSearch
// ========================================================
// 描述:人脸识别mMultiSearch
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class mMultiSearch : FaceSearchBase
{
private void Start()
{
MultiSearchDemo(groupIdList, () =>
{
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 人脸搜索 M:N 识别
/// </summary>
/// <param name="callback"></param>
public void MultiSearchDemo(string groupIdList, Action callback = null)
{
var imageType = "BASE64";
try
{
// 调用人脸搜索 M:N 识别,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.MultiSearch(image, imageType, groupIdList);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"max_face_num", 10},
{"match_threshold", 70},
{"quality_control", "NORMAL"},
{"liveness_control", "NONE"},
{"max_user_num", 20}
};
// 带参数调用人脸搜索 M:N 识别
var result = client.MultiSearch(GetImage("string"), imageType, groupIdList, options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
/// <summary>
/// 身份验证
/// </summary>
public void PersonVerifyDemo(string idCardNumber, string name, Action callback = null)
{
var imageType = "BASE64";
try
{
// 调用身份验证,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.PersonVerify(image, imageType, idCardNumber, name);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"quality_control", "NORMAL"},
{"liveness_control", "NONE"}
};
// 带参数调用身份验证
var result = client.PersonVerify(GetImage("string"), imageType, idCardNumber, name, options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback();
}
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
}
/// <summary>
/// 语音校验码接口
/// 此接口主要用于生成随机码,用于视频的语音识别校验使用,
/// 以判断视频的即时性,而非事先录制的,提升作弊的难度。
/// </summary>
public void VideoSessioncodeDemo( Action callback = null)
{
// 调用语音校验码接口,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.VideoSessioncode();
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"appid", APP_ID}
};
// 带参数调用语音校验码接口
var result = client.VideoSessioncode(options);
Debug.Log(result);
WriteResults(result);
if (callback != null)
{
callback();
}
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
}
/// <summary>
/// 仅供 人脸检测 和人脸对比使用
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public string ReadImg(string img)
{
return Convert.ToBase64String(File.ReadAllBytes(img));
}
/// <summary>
/// 人脸对比
/// </summary>
public void Comparedemo(string img1, string img2)
{
var faces = new JArray
{
new JObject
{
{"image", ReadImg(img1)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
},
new JObject
{
{"image", ReadImg(img2)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
}
};
var result = client.Match(faces);
Console.Write(result);
}
}
人脸识别mMultiSearchJson
// ========================================================
// 描述:人脸识别mMultiSearch JSON
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class mMultiSearchJson
{
static Person player;
public static string JsonToFrom()
{
string path;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return resultStr();
}
public static string resultStr() {
string str = "";
str += "查询出" + player.result.face_num + "张人脸 \n";
for (int i = 0; i < player.result.face_num; i++)
{
if (player.result.face_list[i].user_list.Length < 1)
{
str += "第" + (i + 1) + "个人脸在数据库中没有数据. \n";
continue;
}
str += "第" + (i + 1) + "个人在当前人脸在数据库中的位置 " +
player.result.face_list[i].user_list[0].group_id + " 分组,\n"
+ "用户名是 " + player.result.face_list[i].user_list[0].user_id + ",\n"
+ "注册用户时携带的用户信息是 " + player.result.face_list[i].user_list[0].user_info + ",\n"
+ "用户的匹配可信度 " + player.result.face_list[i].user_list[0].score.ToString("0.00") + ".\n";
}
return str;
}
[Serializable]
public class Person
{
public int error_code;
public string error_msg;
public long log_id;
public long timestamp;
public float cached;
public result result;
public Person(int _error_code, string _error_msg, long _log_id, long _timestamp, float _cached, result _result)
{
error_code = _error_code;
error_msg = _error_msg;
log_id = _log_id;
timestamp = _timestamp;
cached = _cached;
result = _result;
}
}
[Serializable]
public class result
{
public int face_num;
public face_list[] face_list;
public result(int _face_num, face_list[] _face_list)
{
face_num = _face_num;
face_list = _face_list;
}
}
[Serializable]
public class face_list
{
public string face_token;
public location location;
public user_list[] user_list;
public face_list(string _face_token, location _location, user_list[] _user_list)
{
face_token = _face_token;
location = _location;
user_list = _user_list;
}
}
[Serializable]
public class location {
public float left;
public float top;
public float width;
public float height;
public float rotation;
public location(float _left, float _top, float _width, float _height, float _rotation) {
left = _left;
top = _top;
width = _width;
height = _height;
rotation = _rotation;
}
}
[Serializable]
public class user_list
{
public string group_id;
public string user_id;
public string user_info;
public float score;
public user_list(string _group_id, string _user_id, string _user_info, float _score)
{
group_id = _group_id;
user_id = _user_id;
user_info = _user_info;
score = _score;
}
}
}
PersonVerify
// ========================================================
// 描述:身份认证
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PersonVerify : FaceSearchBase
{
private void Start()
{
PersonVerifyDemo("", "", () => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 身份验证
/// </summary>
public void PersonVerifyDemo(string idCardNumber, string name, Action callback = null)
{
var imageType = "BASE64";
try
{
// 调用身份验证,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.PersonVerify(image, imageType, idCardNumber, name);
// Console.WriteLine(result);
// 如果有可选参数
var options = new Dictionary<string, object>{
{"quality_control", "NORMAL"},
{"liveness_control", "NONE"}
};
// 带参数调用身份验证
var result = client.PersonVerify(GetImage("string"), imageType, idCardNumber, name, options);
Debug.Log(result);
//WriteImageResult(result);
if (callback != null)
{
callback();
}
}
catch (Exception ex)
{
Debug.Log("unity" + ex);
}
}
/// <summary>
/// 语音校验码接口
/// 此接口主要用于生成随机码,用于视频的语音识别校验使用,
/// 以判断视频的即时性,而非事先录制的,提升作弊的难度。
/// </summary>
public void VideoSessioncodeDemo( Action callback = null)
{
// 调用语音校验码接口,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.VideoSessioncode();
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"appid", APP_ID}
};
// 带参数调用语音校验码接口
var result = client.VideoSessioncode(options);
Debug.Log(result);
WriteResults(result);
if (callback != null)
{
callback();
}
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
}
/// <summary>
/// 仅供 人脸检测 和人脸对比使用
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public string ReadImg(string img)
{
return Convert.ToBase64String(File.ReadAllBytes(img));
}
/// <summary>
/// 人脸对比
/// </summary>
public void Comparedemo(string img1, string img2)
{
var faces = new JArray
{
new JObject
{
{"image", ReadImg(img1)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
},
new JObject
{
{"image", ReadImg(img2)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
}
};
var result = client.Match(faces);
Console.Write(result);
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class VideoSessionco : FaceSearchBase
{
private void Start()
{
VideoSessioncodeDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
/// <summary>
/// 语音校验码接口
/// 此接口主要用于生成随机码,用于视频的语音识别校验使用,
/// 以判断视频的即时性,而非事先录制的,提升作弊的难度。
/// </summary>
public void VideoSessioncodeDemo( Action callback = null)
{
// 调用语音校验码接口,可能会抛出网络等异常,请使用try/catch捕获
// var result = client.VideoSessioncode();
// Console.WriteLine(result);
// 如果有可选参数
try
{
var options = new Dictionary<string, object>{
{"appid", APP_ID}
};
// 带参数调用语音校验码接口
var result = client.VideoSessioncode(options);
Debug.Log(result);
WriteResults(result);
if (callback != null)
{
callback();
}
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
}
/// <summary>
/// 仅供 人脸检测 和人脸对比使用
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public string ReadImg(string img)
{
return Convert.ToBase64String(File.ReadAllBytes(img));
}
/// <summary>
/// 人脸对比
/// </summary>
public void Comparedemo(string img1, string img2)
{
var faces = new JArray
{
new JObject
{
{"image", ReadImg(img1)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
},
new JObject
{
{"image", ReadImg(img2)},
{"image_type", "BASE64"},
{"face_type", "LIVE"},
{"quality_control", "LOW"},
{"liveness_control", "NONE"},
}
};
var result = client.Match(faces);
Console.Write(result);
}
}
图片识别 ImageRecognition
// ========================================================
// 描述:图片识别
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using Baidu.Aip.ImageClassify;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ImageRecognition : RecognitionBase
{
protected const string API_KEY = "wecrovEMubUNSkgXUXR7GMTU";
protected const string SECRET_KEY = "jpYuLOL2IEwnWlGdVLG2BBF2gvGXFSy6";
ImageClassify client;
private void Awake()
{
client = new ImageClassify(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
private void Start()
{
AdvancedGeneralDemo(() => {
SceneManager.LoadScene(Configures.SpeechTts);
});
}
public void AdvancedGeneralDemo(Action callback)
{
Debug.Log(" unity 开始识别");
try
{
// 如果有可选参数
var options = new Dictionary<string, object>{
{"baike_num",1}
};
// 带参数调用通用物体识别
var result = client.AdvancedGeneral(GetImage(), options);
Debug.Log("unity" + result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
图片识别 joson ImageResultJson
// ========================================================
// 描述:图片识别 joson
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class ImageResultJson
{
static Person player;
static string path;
public static string JsonToFrom()
{
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path+ Configures.JsonsName);
player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return (player.result[0].root + ". \n" + player.result[0].baike_info.description);
}
[Serializable]
public class result
{
public double score;
public string root;
public Baike_info baike_info;
public string keyword;
public result(double _score, string _root, Baike_info baike_info, string _keyword)
{
score = _score;
root = _root;
this.baike_info = baike_info;
keyword = _keyword;
}
}
[Serializable]
public class Baike_info
{
public string baike_url;
public string image_url;
public string description;
public Baike_info(string _baike_url, string _image_url, string _description)
{
baike_url = _baike_url;
image_url = _image_url;
description = _description;
}
}
[Serializable]
public class Person
{
public long log_id;
public int result_num;
public result[] result;
public Person(long _log_id, int _result_num, result[] _result)
{
log_id = _log_id;
result_num = _result_num;
result = _result;
}
}
}
语音 识别技术 Speech_Asr
// ========================================================
// 描述:语音 识别技术
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections.Generic;
using UnityEngine;
using Baidu.Aip.Speech;
using System.IO;
using System;
using UnityEngine.SceneManagement;
/// <summary>
/// 语音 识别技术
/// </summary>
public class Speech_Asr : RecognitionBase
{
// 设置APPID/AK/SK
private const string APP_ID = "18644008";
private const string API_KEY = "B3Ba49z6jqoZcAuabeoe1TG5";
private const string SECRET_KEY = "eSTyl1TABtbwGEI9ki4KhGm5nz2fjdf6";
Asr client;
private void Awake()
{
client = new Asr(APP_ID, API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
void Start()
{
AsrData(() =>
{
SceneManager.LoadScene(Configures.SpeechTts);
});
}
// 识别本地文件
public void AsrData(Action callback)
{
Debug.Log("开始识别");
var data = File.ReadAllBytes(GetAudioPath()+Configures.AudioName);
// 可选参数
try
{
var options = new Dictionary<string, object>
{
{"dev_pid", 1537}
};
client.Timeout = 120000; // 若语音较长,建议设置更大的超时时间. ms
var result = client.Recognize(data, "wav", 16000, options);
Debug.Log(result);
WriteResults(result);
}
catch (Exception e)
{
WriteExceptions(e.ToString());
Debug.Log("unity" + e);
}
if (callback != null)
{
callback();
}
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
public class ReadResult : MonoBehaviour
{
Speech_Tts _Speech_Tts;
LoadAudio _LoadAudio;
SpeechTtsController _UIsController;
string Resultjson;
private void Start()
{
_Speech_Tts = gameObject.GetComponent<Speech_Tts>();
_LoadAudio = gameObject.GetComponent<LoadAudio>();
_UIsController = GameObject.Find("UIController").GetComponent<SpeechTtsController>();
GetText();
_UIsController.ShowResult(Resultjson);
}
void GetText() {
if (PlayerPrefs.GetString(Configures.haveException)=="true")
{
Resultjson = ResdException();
return;
}
switch (PlayerPrefs.GetInt(Configures.SceceID))
{
case 0://图片识别
Resultjson = ImageResultJson.JsonToFrom();
break;
case 1://文字识别
Resultjson = CharResulttoJson.JsonToFrom();
break;
case 2:// 语音识别
Resultjson = AsrResultJson.JsonToFrom();
break;
case 3://人脸检测
Resultjson = FaceResultJson.JsonToFrom();
break;
case 4://人脸搜索 1:N
Resultjson = FaceSearchOneVSMultiJson.JsonToFrom();
break;
case 5://人脸搜索 N:M
Resultjson = mMultiSearchJson.JsonToFrom();
break;
case 6://人脸对比
Resultjson = mCompareJson.JsonToFrom();
break;
case 8://人体检测
Resultjson = BodyAnalysisBodyJson.JsonToFrom();
break;
case 9://人体检测
Resultjson = HandRecognitionJson.JsonToFrom();
break;
default:
Debug.Log("这里出现问题" + PlayerPrefs.GetInt(Configures.SceceID));
break;
}
}
public void StartRead(AudioSource _AudioSource )
{
if (_AudioSource.clip==null)
{
_Speech_Tts.SetTest(Resultjson);
_Speech_Tts.Tts();
}
string path;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.SpeechAudios_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.SpeechAudios_Unity;
#endif
StartCoroutine(_LoadAudio.LoadMusic(path + Configures.AudioName,(clip)=> {
_AudioSource.clip = clip;
_AudioSource.Play();
}));
}
string ResdException() {
#if UNITY_ANDROID && !UNITY_EDITOR
var path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
var path = Configures.JsonPath_Unity;
#endif
return File.ReadAllText(path + Configures.JsonsName);
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using System.IO;
using System;
public static class AsrResultJson
{
public static string JsonToFrom()
{
try
{
string path = null;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
string jsonStr = File.ReadAllText(path + Configures.JsonsName);
Person player = JsonUtility.FromJson<Person>(jsonStr);
JsonUtility.FromJsonOverwrite(jsonStr, player);
return (player.result[0].ToString());
}
catch (Exception e)
{
return (e.ToString());
throw;
}
}
[Serializable]
public class Person
{
public string corpus_no;
public string err_msg;
public int err_no;
public string[] result;
public string sn;
public Person(string _corpus_no, string _err_msg,int _err_no, string[] _result, string _sn)
{
corpus_no = _corpus_no;
err_msg = _err_msg;
err_no = _err_no;
result = _result;
sn = _sn;
}
}
}
语音合成技术
// ========================================================
// 描述:语音合成技术
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Baidu.Aip.Speech;
using System.IO;
using UnityEditor;
using System;
/// <summary>
/// 语音合成技术
/// </summary>
public class Speech_Tts : RecognitionBase
{
// 设置APPID/AK/SK
private const string APP_ID = "18644008";
private const string API_KEY = "B3Ba49z6jqoZcAuabeoe1TG5";
private const string SECRET_KEY = "eSTyl1TABtbwGEI9ki4KhGm5nz2fjdf6";
Tts client;
string SpeechText;
void Awake()
{
client = new Tts(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
public void SetTest(string _text) {
SpeechText =_text;
}
public void Tts()
{
try
{
// 可选参数
var option = new Dictionary<string, object>()
{
{"spd", 5}, // 语速,取值0-9,默认为5中语速
{"pit", 5}, //音调,取值0-9,默认为5中语调
{"vol", 7}, // 音量,取值0-15,默认为5中音量
{"per", 4} // 发音人选择, 0为女声,1为男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女
};
var result = client.Synthesis(SpeechText, option);
if (result.ErrorCode == 0) // 或 result.Success
{
File.WriteAllBytes(GetAudioPath() + Configures.AudioName, result.Data);
}
}
catch (Exception e)
{
WriteExceptions(e.ToString());
}
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SpeechTtsController : MonoBehaviour
{
public Button back;
public Button Speech;
public GameObject AudioPlayPanel;
public GameObject Player_2D;
public Button Pusebtn;
public Sprite PuseSP;
public Sprite PlaySP;
public Button Stopbtn;
public RectTransform ResultContentHeight;
public Text resultText;
private AudioSource _AudioSource;
private bool CurrentPlay = true;
private float playTime = 0;
ReadResult _ReadImageResult;
private void Start()
{
_ReadImageResult = GameObject.Find("GameController").GetComponent<ReadResult>();
_AudioSource = GameObject.Find("AudioSource").GetComponent<AudioSource>();
Speech.onClick.AddListener(() =>{
_ReadImageResult.StartRead(_AudioSource);
AudioPlayPanel.SetActive(true);
Player_2D.SetActive(true);
CurrentPlay = true;
Pusebtn.image.sprite = PuseSP;
});
back.onClick.AddListener(()=> {
LoadScenID(PlayerPrefs.GetInt(Configures.SceceID));
});
Pusebtn.onClick.AddListener(()=> {
if (CurrentPlay)
{
CurrentPlay = false;
Pusebtn.image.sprite = PlaySP;
_AudioSource.Pause();
}
else
{
CurrentPlay = true;
Pusebtn.image.sprite = PuseSP;
_AudioSource.Play();
}
});
Stopbtn.onClick.AddListener(StopClick);
AudioPlayPanel.SetActive(false);
Player_2D.SetActive(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
StopClick();
}
if (_AudioSource != null && _AudioSource.clip != null &&CurrentPlay)
{
playTime += Time.deltaTime;
if (playTime >= _AudioSource.clip.length)
{
playTime = 0;
_AudioSource.Stop();
CurrentPlay = false;
Pusebtn.image.sprite = PlaySP;
}
}
}
void StopClick() {
CurrentPlay = false;
_AudioSource.Stop();
AudioPlayPanel.SetActive(false);
Player_2D.SetActive(false);
}
void SetResultContentHeight(string result)
{
string str = null;
for (int i = 0; i < result.Length; i++)
{
if (i % 30 == 0 && i != 0)
{
str += "\n";
}
else
{
str += result[i];
}
}
string[] striparr = str.Split('\n');
ResultContentHeight.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, striparr.Length * (resultText.fontSize+10));
}
public void ShowResult(string resultjson)
{
SetResultContentHeight(resultjson);
resultText.text = resultjson;
}
public void LoadScenID(int id)
{
switch (id)
{
case 0://图片识别
case 1://文字识别
case 3://人脸检测
case 4://人脸搜索 1:N
case 5://活体检测 N:M
case 6://人脸对比
case 7://人脸注册
case 8://人体检测
case 9://人体检测
SceneManager.LoadScene(Configures.WebCameraScence);
break;
case 2:// 语音识别
SceneManager.LoadScene(Configures.MicPhoneScence);
break;
default:
break;
}
}
}
识别 base 类 很重要 RecognitionBase
// ========================================================
// 描述:识别 base 类
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System;
using System.IO;
using UnityEngine;
public class RecognitionBase : MonoBehaviour
{
protected byte[] GetImage()
{
byte[] image = File.ReadAllBytes(GetImagePath() + Configures.pictureName);
return image;
}
protected string GetImage(string _name)
{
//读取
FileInfo file = new FileInfo(GetImagePath() + Configures.pictureName);
var stream = file.OpenRead();
byte[] buffer = new byte[file.Length];
//读取图片字节流
stream.Read(buffer, 0, Convert.ToInt32(file.Length));
//base64字符串
string image = Convert.ToBase64String(buffer);
return image;
}
protected string[] GetImage(string _name1, string _name2)
{
string[] image=new string[2];
FileInfo file;
for (int i = 0; i < 2; i++)
{
if (i == 0)
{
//读取
file = new FileInfo(GetImagePath() + Configures.pictureName);
}
else {
//读取
file = new FileInfo(GetImagePath() + Configures.pictureName_Copy);
}
var stream = file.OpenRead();
byte[] buffer = new byte[file.Length];
//读取图片字节流
stream.Read(buffer, 0, Convert.ToInt32(file.Length));
//base64字符串
image[i] = Convert.ToBase64String(buffer);
}
return image;
}
string GetImagePath() {
string path = null;
#if UNITY_ANDROID && !UNITY_EDITOR
path =Configures.PhotoPath_Andriod ;
Debug.Log("unity这里安卓设备 获取了一张图片"+path);
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.PhotoPath_Unity;
Debug.Log("unity电脑上运行 获取了一张图片地址" + path);
#endif
return path;
}
protected string GetAudioPath()
{
string path = null;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.SpeechAudios_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.SpeechAudios_Unity;
#endif
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
return path;
}
protected void WriteResults(Newtonsoft.Json.Linq.JObject result) {
PlayerPrefs.SetString(Configures.haveException, "false");
ResultWriteJson(GetSavepath(), Configures.JsonsName, result);
}
string GetSavepath() {
string path = null;
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.JsonPath_Andriod ;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.JsonPath_Unity;
#endif
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
protected void WriteExceptions(string result) {
PlayerPrefs.SetString(Configures.haveException, "true");
File.WriteAllText(GetSavepath() + Configures.JsonsName, result);
}
/// <summary>
/// 将结果写入本地
/// </summary>
/// <param name="result"></param>
void ResultWriteJson(string path, string name, Newtonsoft.Json.Linq.JObject result)
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
File.WriteAllText(path + name, result.ToString());
}
}
MainScenController
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
public class MainScenController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameObject.Find("Canvas").transform.Find("UserAddPanel").gameObject.SetActive(false);
switch (PlayerPrefs.GetInt(Configures.SceceID))
{
case 0://图片识别
gameObject.AddComponent<ImageRecognition>();
break;
case 1://文字识别
gameObject.AddComponent<CharacterRecognition>();
break;
case 2:// 语音识别
gameObject.AddComponent<Speech_Asr>();
break;
case 3://人脸检测
gameObject.AddComponent<FaceDetect>();
break;
case 4://人脸搜索1 : N
gameObject.AddComponent<mFaceSearchOneVSMulti>();
break;
case 5:///人脸搜索 N:M
gameObject.AddComponent<mMultiSearch>();
break;
case 6:
//人脸对比
gameObject.AddComponent<mCompare>();
break;
case 7:
//人脸注册
gameObject.AddComponent<FaceSearchTool>();
gameObject.AddComponent<FaceAddUI>();
break;
case 8:
//人体分析
gameObject.AddComponent<BodyAnalysisBody>();
break;
case 9:
//手势识别
gameObject.AddComponent<HandRecognition>();
break;
default:
Debug.Log(PlayerPrefs.GetInt(Configures.SceceID) + " 不存在");
break;
}
}
}
StartScenceController
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using UnityEditor;
using UnityEngine.SceneManagement;
public class StartScenceController : MonoBehaviour
{
public Button[] mMenuButtons;
private void Awake()
{
PlayerPrefs.DeleteAll();
delete();
}
private void Start()
{
for (int i = 0; i < mMenuButtons.Length; i++)
{
int id = i;
mMenuButtons[i].onClick.AddListener(() =>
{
BtnAddListener(id);
});
}
}
void delete() {
#if UNITY_ANDROID && !UNITY_EDITOR
var path = Configures.PhotoPath_Andriod;
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
var path = Configures.PhotoPath_Unity;
#endif
if (File.Exists(path + Configures.pictureName))
{
File.Delete(path + Configures.pictureName);
}
if (File.Exists(path + Configures.pictureName + ".meta"))
{
File.Delete(path + Configures.pictureName + ".meta");
}
if (File.Exists(path + Configures.pictureName_Copy))
{
File.Delete(path + Configures.pictureName_Copy);
}
if (File.Exists(path + Configures.pictureName_Copy+".meta"))
{
File.Delete(path + Configures.pictureName_Copy + ".meta");
}
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}
void BtnAddListener(int id) {
PlayerPrefs.SetInt(Configures.SceceID, id);
LoadScenID(id);
}
public void LoadScenID(int id)
{
switch (id)
{
case 0://图片识别
case 1://文字识别
case 3://人脸检测
case 4://人脸搜索 1:N
case 5://活体检测 N:M
case 6://人脸对比
case 7://人脸注册
case 8://人体检测
case 9://人体检测
SceneManager.LoadScene(Configures.WebCameraScence);
break;
case 2:// 语音识别
SceneManager.LoadScene(Configures.MicPhoneScence);
break;
default:
break;
}
}
}
Configures
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Configures
{
public static string PhotoPath_Andriod = Application.persistentDataPath + "/Photo";
public static string PhotoPath_Unity = Application.streamingAssetsPath + "/Photo";
public static string JsonPath_Andriod = Application.persistentDataPath + "/Data";
public static string JsonPath_Unity = Application.streamingAssetsPath + "/Data";
public static string SpeechAudios_Andriod = Application.persistentDataPath + "/Audios";
public static string SpeechAudios_Unity = Application.streamingAssetsPath + "/Audios";
public static string pictureName = "/Screenshot.png";
public static string pictureName_Copy = "/CopyScreenshot.png";
public static string JsonsName = "/jsondata.txt";
public static string AudioName = "/sound.mp3";
/// <summary>
/// 开始场景
/// </summary>
public static string StartScence = "StartScence";
/// <summary>
/// 摄像机场景
/// </summary>
public static string WebCameraScence = "WebCaneraScence";
/// <summary>
/// 录音场景
/// </summary>
public static string MicPhoneScence = "MicPhoneRecord";
/// <summary>
/// 语音合成场景
/// </summary>
public static string SpeechTts = "SpeechTts";
/// <summary>
/// 识别场景
/// </summary>
public static string BaseScence = "MainScence";
public static string SceceID;
public static string CameraID="CameraID";
public static string haveException = "HaveException";
}
摄像机类
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 获取摄像机权限
/// 屏幕显示
/// </summary>
public class WebCamera : MonoBehaviour
{
public RawImage rawImage;
public void StopIE()
{
StopCoroutine(CallWebCam(0));
}
public IEnumerator CallWebCam(int _id)
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
while (devices.Length<=0)
{
devices = WebCamTexture.devices;
}
if (devices != null && devices.Length > 0)
{
_id = devices.Length > 1 ? _id : 0;
string deviceName = devices[_id].name;
WebCamTexture CameraTexture = new WebCamTexture(deviceName, Screen.width, Screen.height);
rawImage.texture = CameraTexture;
CameraTexture.Play();
}
}
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class WebCameraCtl : MonoBehaviour
{
public Button GetPhotoBtn;
public Button BackBtn;
public Button ChangeCameraBtn;
SavePhoto mSavePhoto;
WebCamera mWebCamera;
CopyImage mCopyImage;
int CameraID=0;
private void Start()
{
mSavePhoto= GetComponent<SavePhoto>();
mWebCamera = GetComponent<WebCamera>();
mCopyImage = GetComponent<CopyImage>();
SetActive(true);
GetPhotoBtn.onClick.AddListener(GetPhoto);
BackBtn.onClick.AddListener(()=> {
SceneManager.LoadScene(Configures.StartScence);
});
CameraID = PlayerPrefs.GetInt(Configures.CameraID);
ChangeCameraBtn.onClick.AddListener(()=>{
CameraID = CameraID == 0 ? 1 : 0;
PlayerPrefs.SetInt(Configures.CameraID, CameraID);
OpenCamera(CameraID);
});
OpenCamera(CameraID);
}
public void GetPhoto()
{
SetActive(false);
StartCoroutine(mSavePhoto.CaptureScreenshot(new Rect(0, 0, Screen.width, Screen.height), () => {
//判断是不是人脸对比场景
if (PlayerPrefs.GetInt(Configures.SceceID)==6)
{
var bytes = mCopyImage.toRead(Configures.pictureName_Copy);
if (bytes == null) {
mCopyImage.toPase();
Debug.Log("第一张图片,请继续拍照");
SceneManager.LoadScene(Configures.WebCameraScence);
return;
}
}
SceneManager.LoadScene(Configures.BaseScence);
}));
}
void SetActive(bool active)
{
GetPhotoBtn.gameObject.SetActive(active);
BackBtn.gameObject.SetActive(active);
ChangeCameraBtn.gameObject.SetActive(active);
}
private void OpenCamera(int _id) {
mWebCamera.StopIE();
StartCoroutine(mWebCamera.CallWebCam(_id));
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
/// <summary>
/// 仅用于人脸对比
/// </summary>
public class CopyImage : MonoBehaviour
{
public byte[] toRead(string name) {
string path = null;
#if UNITY_ANDROID && !UNITY_EDITOR
path =Configures.PhotoPath_Andriod ;
Debug.Log("unity这里安卓设备 获取了一张图片"+path);
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.PhotoPath_Unity;
#endif
byte[] bytes = null;
try
{
bytes = File.ReadAllBytes(path + name);
}
catch (Exception e)
{
Debug.Log(e);
}
return bytes;
}
public void toPase()
{
var bytes = toRead(Configures.pictureName);
if (bytes != null && bytes.Length > 0)
{
#if UNITY_ANDROID && !UNITY_EDITOR
var path = Configures.PhotoPath_Andriod;
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
File.WriteAllBytes( path+Configures.pictureName_Copy, bytes);
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
var path = Configures.PhotoPath_Unity;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
File.WriteAllBytes(path + Configures.pictureName_Copy, bytes);
AssetDatabase.Refresh();
#endif
}
}
}
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System.Collections;
using UnityEditor;
using UnityEngine;
using System;
using System.IO;
/// <summary>
/// 截屏脚本
/// </summary>
public class SavePhoto : MonoBehaviour
{
string path;
/// <summary>
/// 截取屏幕
/// </summary>
/// <returns>The screenshot2.</returns>
/// <param name="rect">Rect.截图的区域,左下角为o点</param>
public IEnumerator CaptureScreenshot(Rect rect, Action callback=null)
{
yield return new WaitForEndOfFrame();
// 先创建一个的空纹理,大小可根据实现需要来设置
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
// 读取屏幕像素信息并存储为纹理数据,
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
// 然后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
if (bytes != null && bytes.Length > 0)
{
#if UNITY_ANDROID && !UNITY_EDITOR
path = Configures.PhotoPath_Andriod;
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
File.WriteAllBytes( path+Configures.pictureName, bytes);
#elif UNITY_IPHONE
Debug.Log("unity这里苹果设备");
#elif UNITY_EDITOR
path = Configures.PhotoPath_Unity;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
File.WriteAllBytes(path+Configures.pictureName, bytes);
AssetDatabase.Refresh();
#endif
}
if (callback != null) callback();
}
}
QuitGame
// ========================================================
// 描述:
// 作者:qinglong
// 创建时间:2020-04-07 11:31:27
// 版 本:1.0
// ========================================================
using System;
using UnityEngine;
using UnityEngine.UI;
public class QuitGame : MonoBehaviour
{
public GameObject Quitprefab;
GameObject Quit;
Transform canvers;
public static QuitGame instance =null;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);
}
/// <summary>
/// 添加监听
/// </summary>
/// <param name="_Quit"></param>
void AddListener(GameObject _Quit)
{
_Quit.transform.Find("BG/sure").GetComponent<Button>().onClick.AddListener(()=> {
Application.Quit();
});
_Quit.transform.Find("BG/back").GetComponent<Button>().onClick.AddListener(() => {
Destroy(_Quit.gameObject);
Quit = null;
});
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
try
{
//dang
if (Quit != null)
{
return;
}
canvers = GameObject.Find("Canvas").transform;
Quit = Instantiate(Quitprefab);
// 设置锚点
Quit.transform.SetParent(canvers);
RectTransform quitRectT = Quit.GetComponent<RectTransform>();
quitRectT.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
quitRectT.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
quitRectT.anchorMin = Vector2.zero;
quitRectT.anchorMax = Vector2.one;
quitRectT.localScale = new Vector3(1, 1, 1);
AddListener(Quit);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
}
}
以上是所有的代码
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)