VoiceController.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.UIElements;
  6. using System.Runtime.InteropServices;
  7. using Unity.VisualScripting;
  8. public class VoiceController : MonoBehaviour
  9. {
  10. // Start is called once before the first execution of Update after the MonoBehaviour is created
  11. private VisualElement waveForm;
  12. private Button voiceBtn;
  13. private Coroutine waveCoroutine;
  14. private AudioClip audioClip; // 保存的音频
  15. private bool isRecording = false;
  16. private string filePathWav, filePathZip;
  17. public bool isCommandMode = false; // 是否在命令对话模式下,是的话只显示语音按钮
  18. void OnEnable()
  19. {
  20. //Debug.Log("voice controller start");
  21. var root = GetComponent<UIDocument>().rootVisualElement;
  22. var voiceArea = root.Q<VisualElement>("voiceArea");
  23. waveForm = voiceArea.Q<VisualElement>("waveForm");
  24. voiceBtn = voiceArea.Q<Button>("voice");
  25. // root加载完成后,所有element算出位置后再进行计算
  26. root.RegisterCallback<GeometryChangedEvent>(e => OnMainMenuClickGeometryChanged(e));
  27. voiceBtn.RegisterCallback<PointerDownEvent>(e => VoiceBtnPointerDown(e), TrickleDown.TrickleDown); // TrickleDown.TrickleDown参数,确保事件在捕获阶段优先处理。
  28. voiceBtn.RegisterCallback<PointerUpEvent>(e => VoiceBtnPointerUp(e));
  29. }
  30. // Update is called once per frame
  31. void Update()
  32. {
  33. VoiceOnlyCheck();
  34. }
  35. // 只显示语音菜单
  36. public void VoiceOnlyCheck()
  37. {
  38. var root = GetComponent<UIDocument>().rootVisualElement;
  39. var menuArea = root.Q<VisualElement>("menuArea");
  40. var dogMenu = root.Q<VisualElement>("dogMenu");
  41. if (isCommandMode)
  42. {
  43. menuArea.style.display = DisplayStyle.None;
  44. dogMenu.style.display = DisplayStyle.None;
  45. }
  46. else
  47. {
  48. menuArea.style.display = DisplayStyle.Flex;
  49. dogMenu.style.display = DisplayStyle.Flex;
  50. }
  51. }
  52. IEnumerator WaveFormAnimation()
  53. {
  54. while (true)
  55. {
  56. waveForm.style.height = UnityEngine.Random.Range(15f, 30f);
  57. float alpha = UnityEngine.Random.Range(0.6f, 1f);
  58. waveForm.style.unityBackgroundImageTintColor = new Color(1f, 1f, 1f, alpha);
  59. yield return new WaitForSeconds(0.1f);
  60. }
  61. }
  62. void OnMainMenuClickGeometryChanged(GeometryChangedEvent evt)
  63. {
  64. if (waveCoroutine == null)
  65. {
  66. waveCoroutine = StartCoroutine(WaveFormAnimation());
  67. }
  68. }
  69. // 语言控制按键按下的触发事件
  70. void VoiceBtnPointerDown(PointerDownEvent evt)
  71. {
  72. Debug.Log("voice button pointer down.");
  73. HomeController.listenBreak = true;
  74. // 隐藏Dog list
  75. var root = GetComponent<UIDocument>().rootVisualElement;
  76. var dogList = root.Q<VisualElement>("dogMenu").Q<VisualElement>("dogList");
  77. dogList.visible = false;
  78. // 狗动作变化注释镜头
  79. foreach (var dog in HomeController.dogsInScene)
  80. {
  81. dog.animator.SetTrigger("listen");
  82. }
  83. StartRecording();
  84. waveForm.visible = true;
  85. // 如果时间是在声音,就改变Home场景的光照
  86. int hour = System.DateTime.Now.Hour;
  87. if (hour >= 22 || hour < 5) // 深夜时间
  88. {
  89. HomeSunLight.Instance.DogWakeUpLightSetting();
  90. }
  91. }
  92. // 语音控制按键松开事件
  93. void VoiceBtnPointerUp(PointerUpEvent evt)
  94. {
  95. Debug.Log("voice button pointer up.");
  96. //HomeController.listenBreak = false;
  97. waveForm.visible = false;
  98. HomeController.listenBreak = false;
  99. // TODO 以后根据音频识别返回值修改狗的行动
  100. foreach (var dog in HomeController.dogsInScene)
  101. {
  102. dog.animator.SetBool("isListening", false);
  103. }
  104. StopRecording();
  105. }
  106. #region 录音相关
  107. // 开始录音
  108. void StartRecording()
  109. {
  110. if (isRecording) return; // 如果已经在录音,则不再重复开始
  111. // 设置录音文件名和路径
  112. filePathWav = Path.Combine(Application.persistentDataPath, "voice.wav");
  113. filePathZip = Path.Combine(Application.persistentDataPath, "voice.zip");
  114. // 检测目录是否存在不存在就创建
  115. string directoryPath = Path.GetDirectoryName(filePathWav);
  116. if (!Directory.Exists(directoryPath))
  117. {
  118. Directory.CreateDirectory(directoryPath);
  119. }
  120. //删除旧文件
  121. if (File.Exists(filePathWav))
  122. {
  123. File.Delete(filePathWav);
  124. }
  125. if (File.Exists(filePathZip))
  126. {
  127. File.Delete(filePathZip);
  128. }
  129. // 开始录音,最长4秒
  130. audioClip = Microphone.Start(null, false, 4, 44100);
  131. isRecording = true;
  132. Debug.Log("开始录音...");
  133. }
  134. // 停止录音
  135. void StopRecording()
  136. {
  137. if (!isRecording) return; // 如果没有在录音,则直接返回
  138. // 停止录音
  139. Microphone.End(null);
  140. isRecording = false;
  141. Debug.Log("停止录音...");
  142. // 保存录音为WAV文件和ZIP文件
  143. SaveWavFile(filePathWav, audioClip);
  144. Debug.Log("录音已保存到: " + filePathWav);
  145. ZipFileController.ZipFile(filePathWav, filePathZip);
  146. if (isCommandMode)
  147. {
  148. // command模式,调用Home Controller Command的方法上传音频文件
  149. HomeController.Instance.VoiceCommandRequest(filePathZip);
  150. }
  151. else
  152. {
  153. // 非command模式,调用Home Controller Call的方法上传音频文件
  154. HomeController.Instance.VoiceCallRequest(filePathZip);
  155. }
  156. }
  157. // 保存音频文件wav
  158. void SaveWavFile(string path, AudioClip audio) {
  159. // 创建文件流
  160. using (FileStream fileStream = new(path, FileMode.Create))
  161. {
  162. using (BinaryWriter writer = new BinaryWriter(fileStream))
  163. {
  164. // 写入WAV文件头
  165. writer.Write(new char[4] { 'R', 'I', 'F', 'F' }); // RIFF标志
  166. writer.Write(36 + audio.samples * 2); // 文件大小
  167. writer.Write(new char[4] { 'W', 'A', 'V', 'E' }); // WAVE标志
  168. writer.Write(new char[4] { 'f', 'm', 't', ' ' }); // fmt标志
  169. writer.Write(16); // fmt块大小
  170. writer.Write((ushort)1); // 音频格式(PCM)
  171. writer.Write((ushort)audio.channels); // 声道数
  172. writer.Write(audio.frequency); // 采样率
  173. writer.Write(audio.frequency * audio.channels * 2); // 字节率
  174. writer.Write((ushort)(audio.channels * 2)); // 块对齐
  175. writer.Write((ushort)16); // 位深度
  176. writer.Write(new char[4] { 'd', 'a', 't', 'a' }); // data标志
  177. writer.Write(audio.samples * 2); // 数据大小
  178. // 写入音频数据
  179. float[] samples = new float[audio.samples * audio.channels];
  180. audio.GetData(samples, 0);
  181. for (int i = 0; i < samples.Length; i++)
  182. {
  183. writer.Write((short)(samples[i] * short.MaxValue)); // 将浮点数转换为16位整数
  184. }
  185. }
  186. }
  187. }
  188. #endregion
  189. }