VoiceController.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. }
  86. // 语音控制按键松开事件
  87. void VoiceBtnPointerUp(PointerUpEvent evt)
  88. {
  89. Debug.Log("voice button pointer up.");
  90. //HomeController.listenBreak = false;
  91. StopRecording();
  92. waveForm.visible = false;
  93. HomeController.listenBreak = false;
  94. // TODO 以后根据音频识别返回值修改狗的行动
  95. foreach (var dog in HomeController.dogsInScene)
  96. {
  97. dog.animator.SetBool("isListening", false);
  98. }
  99. }
  100. #region 录音相关
  101. // 开始录音
  102. void StartRecording()
  103. {
  104. if (isRecording) return; // 如果已经在录音,则不再重复开始
  105. // 设置录音文件名和路径
  106. filePathWav = Path.Combine(Application.persistentDataPath, "voiceCommand.wav");
  107. filePathZip = Path.Combine(Application.persistentDataPath, "voiceCommand.zip");
  108. // 检测目录是否存在不存在就创建
  109. string directoryPath = Path.GetDirectoryName(filePathWav);
  110. if (!Directory.Exists(directoryPath))
  111. {
  112. Directory.CreateDirectory(directoryPath);
  113. }
  114. //删除旧文件
  115. if (File.Exists(filePathWav))
  116. {
  117. File.Delete(filePathWav);
  118. }
  119. if (File.Exists(filePathZip))
  120. {
  121. File.Delete(filePathZip);
  122. }
  123. // 开始录音,最长4秒
  124. audioClip = Microphone.Start(null, false, 4, 44100);
  125. isRecording = true;
  126. Debug.Log("开始录音...");
  127. }
  128. // 停止录音
  129. void StopRecording()
  130. {
  131. if (!isRecording) return; // 如果没有在录音,则直接返回
  132. // 停止录音
  133. Microphone.End(null);
  134. isRecording = false;
  135. Debug.Log("停止录音...");
  136. // 保存录音为WAV文件和ZIP文件
  137. SaveWavFile(filePathWav, audioClip);
  138. Debug.Log("录音已保存到: " + filePathWav);
  139. ZipFileController.ZipFile(filePathWav, filePathZip);
  140. if (isCommandMode)
  141. {
  142. // 非ommand模式,调用Home Controller Command的方法上传音频文件
  143. HomeController.Instance.VoiceCommandRequest(filePathZip);
  144. }
  145. else
  146. {
  147. // 非command模式,调用Home Controller Call的方法上传音频文件
  148. HomeController.Instance.VoiceCallRequest(filePathZip);
  149. }
  150. }
  151. // 保存音频文件wav
  152. void SaveWavFile(string path, AudioClip audio) {
  153. // 创建文件流
  154. using (FileStream fileStream = new(path, FileMode.Create))
  155. {
  156. using (BinaryWriter writer = new BinaryWriter(fileStream))
  157. {
  158. // 写入WAV文件头
  159. writer.Write(new char[4] { 'R', 'I', 'F', 'F' }); // RIFF标志
  160. writer.Write(36 + audio.samples * 2); // 文件大小
  161. writer.Write(new char[4] { 'W', 'A', 'V', 'E' }); // WAVE标志
  162. writer.Write(new char[4] { 'f', 'm', 't', ' ' }); // fmt标志
  163. writer.Write(16); // fmt块大小
  164. writer.Write((ushort)1); // 音频格式(PCM)
  165. writer.Write((ushort)audio.channels); // 声道数
  166. writer.Write(audio.frequency); // 采样率
  167. writer.Write(audio.frequency * audio.channels * 2); // 字节率
  168. writer.Write((ushort)(audio.channels * 2)); // 块对齐
  169. writer.Write((ushort)16); // 位深度
  170. writer.Write(new char[4] { 'd', 'a', 't', 'a' }); // data标志
  171. writer.Write(audio.samples * 2); // 数据大小
  172. // 写入音频数据
  173. float[] samples = new float[audio.samples * audio.channels];
  174. audio.GetData(samples, 0);
  175. for (int i = 0; i < samples.Length; i++)
  176. {
  177. writer.Write((short)(samples[i] * short.MaxValue)); // 将浮点数转换为16位整数
  178. }
  179. }
  180. }
  181. }
  182. #endregion
  183. }