VoiceController.cs 5.3 KB

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