voice-check-modal.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. "use strict";
  2. const common_vendor = require("../../common/vendor.js");
  3. const recorderManager = common_vendor.index.getRecorderManager();
  4. const _sfc_main = {
  5. name: "VoiceCheckModal",
  6. props: {
  7. visible: {
  8. type: Boolean,
  9. default: false
  10. }
  11. },
  12. data() {
  13. return {
  14. isRecording: false,
  15. waveData: Array(30).fill(20),
  16. recordingTime: 0,
  17. statusMessage: '点击"开始录制"按钮朗读文字',
  18. silenceCounter: 0,
  19. recordingTimer: null,
  20. volumeLevel: 0,
  21. animationTimer: null,
  22. lastVolume: 0,
  23. hasPermission: false,
  24. // 添加录音权限状态
  25. noSoundTimeout: null,
  26. // 添加无声音超时计时器
  27. recordingStarted: false,
  28. // 添加录音开始标志
  29. audioPath: null,
  30. // 添加录音文件路径
  31. platform: "",
  32. // 添加平台标识
  33. isRetrying: false
  34. // 添加重试标记
  35. };
  36. },
  37. methods: {
  38. // 检查录音权限 - 跨平台兼容版本
  39. async checkPermission() {
  40. const systemInfo = common_vendor.index.getSystemInfoSync();
  41. const platform = systemInfo.platform;
  42. try {
  43. if (platform === "ios") {
  44. const res = await new Promise((resolve, reject) => {
  45. common_vendor.index.getSetting({
  46. success: (result) => {
  47. if (result.authSetting["scope.record"]) {
  48. resolve(true);
  49. } else {
  50. common_vendor.index.authorize({
  51. scope: "scope.record",
  52. success: () => resolve(true),
  53. fail: (err) => reject(err)
  54. });
  55. }
  56. },
  57. fail: (err) => reject(err)
  58. });
  59. });
  60. this.hasPermission = true;
  61. return true;
  62. } else {
  63. const res = await common_vendor.index.authorize({
  64. scope: "scope.record"
  65. });
  66. this.hasPermission = true;
  67. return true;
  68. }
  69. } catch (error) {
  70. console.error("权限请求失败:", error);
  71. common_vendor.index.showModal({
  72. title: "提示",
  73. content: "需要录音权限才能进行录音,请在设置中开启录音权限",
  74. confirmText: "去设置",
  75. success: (res) => {
  76. if (res.confirm) {
  77. common_vendor.index.openSetting();
  78. }
  79. }
  80. });
  81. this.hasPermission = false;
  82. return false;
  83. }
  84. },
  85. async startRecording() {
  86. if (!await this.checkPermission()) {
  87. return;
  88. }
  89. this.isRecording = true;
  90. this.recordingTime = 0;
  91. this.silenceCounter = 0;
  92. this.statusMessage = "正在检测声音...";
  93. this.waveData = this.waveData.map(() => 20);
  94. this.lastVolume = 0;
  95. this.recordingStarted = true;
  96. const systemInfo = common_vendor.index.getSystemInfoSync();
  97. const platform = systemInfo.platform;
  98. const recorderOptions = {
  99. duration: 6e4,
  100. // 最长录音时间
  101. format: "mp3",
  102. // 使用mp3格式提高兼容性
  103. frameSize: 5
  104. };
  105. if (platform === "ios") {
  106. recorderOptions.sampleRate = 44100;
  107. recorderOptions.numberOfChannels = 1;
  108. recorderOptions.encodeBitRate = 96e3;
  109. } else {
  110. recorderOptions.sampleRate = 16e3;
  111. recorderOptions.numberOfChannels = 1;
  112. recorderOptions.encodeBitRate = 48e3;
  113. }
  114. recorderManager.start(recorderOptions);
  115. this.recordingTimer = setInterval(() => {
  116. this.recordingTime++;
  117. }, 1e3);
  118. this.animationTimer = setInterval(() => {
  119. if (this.isRecording) {
  120. this.updateWaveform();
  121. }
  122. }, 50);
  123. this.noSoundTimeout = setTimeout(() => {
  124. if (this.silenceCounter > 20) {
  125. this.showNoSoundTip();
  126. }
  127. }, 3e3);
  128. },
  129. stopRecording() {
  130. this.isRecording = false;
  131. this.recordingStarted = false;
  132. recorderManager.stop();
  133. clearInterval(this.recordingTimer);
  134. clearInterval(this.animationTimer);
  135. clearTimeout(this.noSoundTimeout);
  136. this.statusMessage = "录制完成!";
  137. setTimeout(() => {
  138. this.waveData = Array(30).fill(20);
  139. }, 500);
  140. setTimeout(() => {
  141. this.processAudioFile();
  142. this.$emit("complete", {
  143. success: true,
  144. audioPath: this.audioPath,
  145. platform: this.platform
  146. });
  147. }, 300);
  148. },
  149. // 添加音频文件处理方法
  150. processAudioFile() {
  151. if (!this.audioPath)
  152. return;
  153. const systemInfo = common_vendor.index.getSystemInfoSync();
  154. this.platform = systemInfo.platform;
  155. console.log("处理音频文件:", this.audioPath, "平台:", this.platform);
  156. if (this.platform === "ios") {
  157. if (!this.audioPath.startsWith("file://")) {
  158. this.audioPath = "file://" + this.audioPath;
  159. }
  160. } else if (this.platform === "android")
  161. ;
  162. else if (this.platform === "harmony")
  163. ;
  164. common_vendor.index.getFileInfo({
  165. filePath: this.audioPath,
  166. success: (res) => {
  167. console.log("音频文件信息:", res);
  168. if (res.size === 0) {
  169. console.warn("警告: 音频文件大小为0");
  170. }
  171. },
  172. fail: (err) => {
  173. console.error("获取音频文件信息失败:", err);
  174. }
  175. });
  176. },
  177. // 显示无声音提示
  178. showNoSoundTip() {
  179. if (!this.isRecording)
  180. return;
  181. common_vendor.index.showModal({
  182. title: "未检测到声音",
  183. content: "请检查以下问题:\n1. 麦克风是否正常工作\n2. 是否允许使用麦克风\n3. 是否靠近麦克风说话\n4. 说话音量是否足够",
  184. showCancel: true,
  185. cancelText: "重新录制",
  186. confirmText: "继续录制",
  187. success: (res) => {
  188. if (res.cancel) {
  189. this.restartRecording();
  190. } else {
  191. this.continueRecording();
  192. }
  193. }
  194. });
  195. },
  196. // 重新录制方法
  197. restartRecording() {
  198. recorderManager.stop();
  199. clearInterval(this.recordingTimer);
  200. clearInterval(this.animationTimer);
  201. clearTimeout(this.noSoundTimeout);
  202. this.isRecording = false;
  203. this.recordingStarted = false;
  204. this.recordingTime = 0;
  205. this.silenceCounter = 0;
  206. this.volumeLevel = 0;
  207. this.lastVolume = 0;
  208. this.waveData = Array(30).fill(20);
  209. setTimeout(() => {
  210. this.startRecording();
  211. }, 500);
  212. },
  213. // 继续录制方法
  214. continueRecording() {
  215. this.silenceCounter = 0;
  216. this.statusMessage = "正在检测声音...";
  217. clearTimeout(this.noSoundTimeout);
  218. this.noSoundTimeout = setTimeout(() => {
  219. if (this.silenceCounter > 20) {
  220. this.showNoSoundTip();
  221. }
  222. }, 3e3);
  223. },
  224. detectAudio(int16Array) {
  225. const systemInfo = common_vendor.index.getSystemInfoSync();
  226. const platform = systemInfo.platform;
  227. let sum = 0;
  228. let peak = 0;
  229. const blockSize = 128;
  230. for (let i = 0; i < int16Array.length; i += blockSize) {
  231. const end = Math.min(i + blockSize, int16Array.length);
  232. for (let j = i; j < end; j++) {
  233. const absValue = Math.abs(int16Array[j]);
  234. sum += absValue;
  235. peak = Math.max(peak, absValue);
  236. }
  237. }
  238. const avg = sum / int16Array.length;
  239. let SPEAK_THRESHOLD = 500;
  240. let volumeScale = 2e3;
  241. if (platform === "ios") {
  242. SPEAK_THRESHOLD = 300;
  243. volumeScale = 1500;
  244. } else if (platform === "android") {
  245. SPEAK_THRESHOLD = 500;
  246. volumeScale = 2e3;
  247. } else {
  248. SPEAK_THRESHOLD = 400;
  249. volumeScale = 1800;
  250. }
  251. const combinedLevel = (avg * 0.7 + peak * 0.3) / volumeScale;
  252. this.volumeLevel = this.smoothVolume(combinedLevel);
  253. if (avg > SPEAK_THRESHOLD || peak > SPEAK_THRESHOLD * 3) {
  254. this.statusMessage = "检测到声音:录音中...";
  255. this.silenceCounter = 0;
  256. clearTimeout(this.noSoundTimeout);
  257. this.updateWaveform(false);
  258. } else {
  259. this.silenceCounter++;
  260. if (this.silenceCounter > 10) {
  261. this.statusMessage = "未检测到声音,请靠近麦克风并说话...";
  262. if (this.silenceCounter === 30 && this.isRecording) {
  263. this.showNoSoundTip();
  264. }
  265. this.updateWaveform(true);
  266. }
  267. }
  268. },
  269. // 添加音量平滑处理函数
  270. smoothVolume(newVolume) {
  271. const smoothFactor = 0.3;
  272. const smoothedVolume = this.lastVolume + (newVolume - this.lastVolume) * smoothFactor;
  273. this.lastVolume = smoothedVolume;
  274. return Math.min(1, Math.max(0, smoothedVolume));
  275. },
  276. updateWaveform(isSilent = false) {
  277. const systemInfo = common_vendor.index.getSystemInfoSync();
  278. const platform = systemInfo.platform;
  279. let decayFactor = 0.95;
  280. let animationScale = 1;
  281. if (platform === "ios") {
  282. decayFactor = 0.97;
  283. animationScale = 0.9;
  284. } else if (platform === "android") {
  285. decayFactor = 0.95;
  286. animationScale = 1;
  287. } else {
  288. decayFactor = 0.96;
  289. animationScale = 0.95;
  290. }
  291. if (isSilent) {
  292. this.waveData = this.waveData.map((height) => Math.max(20, height * decayFactor));
  293. } else {
  294. const now = Date.now() * 2e-3;
  295. const volumeEffect = this.volumeLevel * animationScale;
  296. const baseHeight = 20 + volumeEffect * 60;
  297. const waveAmplitude = volumeEffect * 40;
  298. this.waveData = this.waveData.map((currentHeight, i) => {
  299. const phase = i * 0.2 + now;
  300. const wave1 = Math.cos(phase) * 0.5;
  301. const wave2 = Math.sin(phase * 1.5) * 0.3;
  302. const randomFactor = Math.random() * 0.1;
  303. const combinedWave = (wave1 + wave2 + randomFactor) * volumeEffect;
  304. const targetHeight = baseHeight + combinedWave * waveAmplitude;
  305. const smoothFactor = platform === "ios" ? 0.3 : 0.4;
  306. const newHeight = currentHeight + (targetHeight - currentHeight) * smoothFactor;
  307. return Math.max(20, Math.min(120, newHeight));
  308. });
  309. }
  310. },
  311. handleConfirm() {
  312. if (!this.isRecording) {
  313. this.startRecording();
  314. } else {
  315. this.stopRecording();
  316. }
  317. },
  318. formatTime(seconds) {
  319. const mins = Math.floor(seconds / 60);
  320. const secs = seconds % 60;
  321. return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  322. }
  323. },
  324. mounted() {
  325. const systemInfo = common_vendor.index.getSystemInfoSync();
  326. const platform = systemInfo.platform;
  327. recorderManager.onError((error) => {
  328. console.error("录音错误:", error);
  329. let errorMessage = "录音出现错误,请检查麦克风权限或重试";
  330. if (platform === "ios") {
  331. if (error.errMsg && error.errMsg.includes("authorize")) {
  332. errorMessage = "iOS需要麦克风权限,请在设置中允许访问麦克风";
  333. } else if (error.errMsg && error.errMsg.includes("busy")) {
  334. errorMessage = "麦克风正被其他应用使用,请关闭其他使用麦克风的应用";
  335. }
  336. } else if (platform === "android") {
  337. if (error.errMsg && error.errMsg.includes("permission")) {
  338. errorMessage = "安卓系统需要麦克风权限,请在设置中允许访问麦克风";
  339. }
  340. } else if (platform === "harmony") {
  341. errorMessage = "请确保已授予麦克风权限并重试";
  342. }
  343. common_vendor.index.showModal({
  344. title: "录音错误",
  345. content: errorMessage,
  346. showCancel: false,
  347. success: () => {
  348. this.stopRecording();
  349. }
  350. });
  351. });
  352. recorderManager.onStart(() => {
  353. console.log("录音开始");
  354. this.recordingStarted = true;
  355. if (platform === "ios") {
  356. setTimeout(() => {
  357. if (this.silenceCounter > 5) {
  358. this.updateWaveform(false);
  359. }
  360. }, 500);
  361. }
  362. });
  363. recorderManager.onFrameRecorded((res) => {
  364. if (!res.frameBuffer || !this.recordingStarted)
  365. return;
  366. try {
  367. const int16Array = new Int16Array(res.frameBuffer);
  368. this.detectAudio(int16Array);
  369. } catch (error) {
  370. console.error("处理音频帧数据错误:", error);
  371. this.updateWaveform(false);
  372. }
  373. });
  374. recorderManager.onStop((res) => {
  375. this.audioPath = res.tempFilePath;
  376. this.isRecording = false;
  377. this.recordingStarted = false;
  378. clearInterval(this.recordingTimer);
  379. clearInterval(this.animationTimer);
  380. clearTimeout(this.noSoundTimeout);
  381. this.statusMessage = "录制完成!";
  382. if (res.tempFilePath) {
  383. console.log("录音文件路径:", res.tempFilePath);
  384. if (platform === "ios" && !res.tempFilePath.startsWith("file://")) {
  385. this.audioPath = "file://" + res.tempFilePath;
  386. } else {
  387. this.audioPath = res.tempFilePath;
  388. }
  389. } else {
  390. console.error("未获取到录音文件路径");
  391. common_vendor.index.showToast({
  392. title: "录音保存失败",
  393. icon: "none"
  394. });
  395. }
  396. });
  397. recorderManager.onInterruptionBegin && recorderManager.onInterruptionBegin(() => {
  398. console.log("录音被中断");
  399. this.statusMessage = "录音被中断,请重试";
  400. this.stopRecording();
  401. });
  402. recorderManager.onInterruptionEnd && recorderManager.onInterruptionEnd(() => {
  403. console.log("录音中断结束");
  404. });
  405. },
  406. beforeDestroy() {
  407. clearInterval(this.recordingTimer);
  408. clearInterval(this.animationTimer);
  409. clearTimeout(this.noSoundTimeout);
  410. if (this.isRecording) {
  411. recorderManager.stop();
  412. }
  413. try {
  414. this.isRecording = false;
  415. this.recordingStarted = false;
  416. } catch (error) {
  417. console.error("清理资源时出错:", error);
  418. }
  419. }
  420. };
  421. function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  422. return common_vendor.e({
  423. a: $props.visible
  424. }, $props.visible ? common_vendor.e({
  425. b: $data.isRecording
  426. }, $data.isRecording ? {
  427. c: common_vendor.f($data.waveData, (item, index, i0) => {
  428. return {
  429. a: index,
  430. b: item + "rpx"
  431. };
  432. })
  433. } : {}, {
  434. d: common_vendor.t($data.isRecording ? "停止录制" : "开始录制"),
  435. e: common_vendor.o((...args) => $options.handleConfirm && $options.handleConfirm(...args)),
  436. f: common_vendor.t($data.statusMessage)
  437. }) : {});
  438. }
  439. const Component = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-ce199c44"]]);
  440. wx.createComponent(Component);