VoiceController.cs 5.2 KB

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