VoiceController.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. void OnEnable()
  18. {
  19. //Debug.Log("voice controller start");
  20. var root = GetComponent<UIDocument>().rootVisualElement;
  21. var voiceArea = root.Q<VisualElement>("voiceArea");
  22. waveForm = voiceArea.Q<VisualElement>("waveForm");
  23. voiceBtn = voiceArea.Q<Button>("voice");
  24. // root加载完成后,所有element算出位置后再进行计算
  25. root.RegisterCallback<GeometryChangedEvent>(e => OnMainMenuClickGeometryChanged(e));
  26. voiceBtn.RegisterCallback<PointerDownEvent>(e => VoiceBtnPointerDown(e), TrickleDown.TrickleDown); // TrickleDown.TrickleDown参数,确保事件在捕获阶段优先处理。
  27. voiceBtn.RegisterCallback<PointerUpEvent>(e => VoiceBtnPointerUp(e));
  28. }
  29. // Update is called once per frame
  30. //void Update()
  31. //{
  32. //}
  33. IEnumerator WaveFormAnimation()
  34. {
  35. while (true)
  36. {
  37. waveForm.style.height = UnityEngine.Random.Range(15f, 30f);
  38. float alpha = UnityEngine.Random.Range(0.6f, 1f);
  39. waveForm.style.unityBackgroundImageTintColor = new Color(1f, 1f, 1f, alpha);
  40. yield return new WaitForSeconds(0.1f);
  41. }
  42. }
  43. void OnMainMenuClickGeometryChanged(GeometryChangedEvent evt)
  44. {
  45. if (waveCoroutine == null)
  46. {
  47. waveCoroutine = StartCoroutine(WaveFormAnimation());
  48. }
  49. }
  50. // 语言控制按键按下的触发事件
  51. void VoiceBtnPointerDown(PointerDownEvent evt)
  52. {
  53. Debug.Log("voice button pointer down.");
  54. HomeController.listenBreak = true;
  55. // 隐藏Dog list
  56. var root = GetComponent<UIDocument>().rootVisualElement;
  57. var dogList = root.Q<VisualElement>("dogMenu").Q<VisualElement>("dogList");
  58. dogList.visible = false;
  59. // 狗动作变化注释镜头
  60. foreach (var dog in HomeController.dogsInScene)
  61. {
  62. dog.animator.SetTrigger("listen");
  63. }
  64. StartRecording();
  65. waveForm.visible = true;
  66. }
  67. // 语音控制按键松开事件
  68. void VoiceBtnPointerUp(PointerUpEvent evt)
  69. {
  70. Debug.Log("voice button pointer up.");
  71. //HomeController.listenBreak = false;
  72. StopRecording();
  73. waveForm.visible = false;
  74. HomeController.listenBreak = false;
  75. // TODO 以后根据音频识别返回值修改狗的行动
  76. foreach (var dog in HomeController.dogsInScene)
  77. {
  78. dog.animator.SetBool("isListening", false);
  79. }
  80. }
  81. #region 录音相关
  82. // 开始录音
  83. void StartRecording()
  84. {
  85. if (isRecording) return; // 如果已经在录音,则不再重复开始
  86. // 设置录音文件名和路径
  87. filePathWav = Path.Combine(Application.persistentDataPath, "voiceCommand.wav");
  88. filePathZip = Path.Combine(Application.persistentDataPath, "voiceCommand.mp3");
  89. // 检测目录是否存在不存在就创建
  90. string directoryPath = Path.GetDirectoryName(filePathWav);
  91. if (!Directory.Exists(directoryPath))
  92. {
  93. Directory.CreateDirectory(directoryPath);
  94. }
  95. //删除旧文件
  96. if (File.Exists(filePathWav))
  97. {
  98. File.Delete(filePathWav);
  99. }
  100. if (File.Exists(filePathZip))
  101. {
  102. File.Delete(filePathZip);
  103. }
  104. // 开始录音,最长4秒
  105. audioClip = Microphone.Start(null, false, 4, 44100);
  106. isRecording = true;
  107. Debug.Log("开始录音...");
  108. }
  109. // 停止录音
  110. void StopRecording()
  111. {
  112. if (!isRecording) return; // 如果没有在录音,则直接返回
  113. // 停止录音
  114. Microphone.End(null);
  115. isRecording = false;
  116. Debug.Log("停止录音...");
  117. // 保存录音为WAV文件
  118. SaveWavFile(filePathWav, audioClip);
  119. Debug.Log("录音已保存到: " + filePathWav);
  120. ZipFileController.ZipFile(filePathWav, filePathZip);
  121. }
  122. // 保存音频文件wav
  123. void SaveWavFile(string path, AudioClip audio) {
  124. // 创建文件流
  125. using (FileStream fileStream = new(path, FileMode.Create))
  126. {
  127. using (BinaryWriter writer = new BinaryWriter(fileStream))
  128. {
  129. // 写入WAV文件头
  130. writer.Write(new char[4] { 'R', 'I', 'F', 'F' }); // RIFF标志
  131. writer.Write(36 + audio.samples * 2); // 文件大小
  132. writer.Write(new char[4] { 'W', 'A', 'V', 'E' }); // WAVE标志
  133. writer.Write(new char[4] { 'f', 'm', 't', ' ' }); // fmt标志
  134. writer.Write(16); // fmt块大小
  135. writer.Write((ushort)1); // 音频格式(PCM)
  136. writer.Write((ushort)audio.channels); // 声道数
  137. writer.Write(audio.frequency); // 采样率
  138. writer.Write(audio.frequency * audio.channels * 2); // 字节率
  139. writer.Write((ushort)(audio.channels * 2)); // 块对齐
  140. writer.Write((ushort)16); // 位深度
  141. writer.Write(new char[4] { 'd', 'a', 't', 'a' }); // data标志
  142. writer.Write(audio.samples * 2); // 数据大小
  143. // 写入音频数据
  144. float[] samples = new float[audio.samples * audio.channels];
  145. audio.GetData(samples, 0);
  146. for (int i = 0; i < samples.Length; i++)
  147. {
  148. writer.Write((short)(samples[i] * short.MaxValue)); // 将浮点数转换为16位整数
  149. }
  150. }
  151. }
  152. }
  153. #endregion
  154. }