VoiceRecording.svelte 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { createEventDispatcher, tick, getContext } from 'svelte';
  4. import { config, settings } from '$lib/stores';
  5. import { blobToFile, calculateSHA256, findWordIndices } from '$lib/utils';
  6. import { transcribeAudio } from '$lib/apis/audio';
  7. const i18n = getContext('i18n');
  8. const dispatch = createEventDispatcher();
  9. export let recording = false;
  10. export let className = ' p-2.5 w-full max-w-full';
  11. let loading = false;
  12. let confirmed = false;
  13. let durationSeconds = 0;
  14. let durationCounter = null;
  15. let transcription = '';
  16. const startDurationCounter = () => {
  17. durationCounter = setInterval(() => {
  18. durationSeconds++;
  19. }, 1000);
  20. };
  21. const stopDurationCounter = () => {
  22. clearInterval(durationCounter);
  23. durationSeconds = 0;
  24. };
  25. $: if (recording) {
  26. startRecording();
  27. } else {
  28. stopRecording();
  29. }
  30. const formatSeconds = (seconds) => {
  31. const minutes = Math.floor(seconds / 60);
  32. const remainingSeconds = seconds % 60;
  33. const formattedSeconds = remainingSeconds < 10 ? `0${remainingSeconds}` : remainingSeconds;
  34. return `${minutes}:${formattedSeconds}`;
  35. };
  36. let stream;
  37. let speechRecognition;
  38. let mediaRecorder;
  39. let audioChunks = [];
  40. const MIN_DECIBELS = -45;
  41. const VISUALIZER_BUFFER_LENGTH = 300;
  42. let visualizerData = Array(VISUALIZER_BUFFER_LENGTH).fill(0);
  43. // Function to calculate the RMS level from time domain data
  44. const calculateRMS = (data: Uint8Array) => {
  45. let sumSquares = 0;
  46. for (let i = 0; i < data.length; i++) {
  47. const normalizedValue = (data[i] - 128) / 128; // Normalize the data
  48. sumSquares += normalizedValue * normalizedValue;
  49. }
  50. return Math.sqrt(sumSquares / data.length);
  51. };
  52. const normalizeRMS = (rms) => {
  53. rms = rms * 10;
  54. const exp = 1.5; // Adjust exponent value; values greater than 1 expand larger numbers more and compress smaller numbers more
  55. const scaledRMS = Math.pow(rms, exp);
  56. // Scale between 0.01 (1%) and 1.0 (100%)
  57. return Math.min(1.0, Math.max(0.01, scaledRMS));
  58. };
  59. const analyseAudio = (stream) => {
  60. const audioContext = new AudioContext();
  61. const audioStreamSource = audioContext.createMediaStreamSource(stream);
  62. const analyser = audioContext.createAnalyser();
  63. analyser.minDecibels = MIN_DECIBELS;
  64. audioStreamSource.connect(analyser);
  65. const bufferLength = analyser.frequencyBinCount;
  66. const domainData = new Uint8Array(bufferLength);
  67. const timeDomainData = new Uint8Array(analyser.fftSize);
  68. let lastSoundTime = Date.now();
  69. const detectSound = () => {
  70. const processFrame = () => {
  71. if (!recording || loading) return;
  72. if (recording && !loading) {
  73. analyser.getByteTimeDomainData(timeDomainData);
  74. analyser.getByteFrequencyData(domainData);
  75. // Calculate RMS level from time domain data
  76. const rmsLevel = calculateRMS(timeDomainData);
  77. // Push the calculated decibel level to visualizerData
  78. visualizerData.push(normalizeRMS(rmsLevel));
  79. // Ensure visualizerData array stays within the buffer length
  80. if (visualizerData.length >= VISUALIZER_BUFFER_LENGTH) {
  81. visualizerData.shift();
  82. }
  83. visualizerData = visualizerData;
  84. // if (domainData.some((value) => value > 0)) {
  85. // lastSoundTime = Date.now();
  86. // }
  87. // if (recording && Date.now() - lastSoundTime > 3000) {
  88. // if ($settings?.speechAutoSend ?? false) {
  89. // confirmRecording();
  90. // }
  91. // }
  92. }
  93. window.requestAnimationFrame(processFrame);
  94. };
  95. window.requestAnimationFrame(processFrame);
  96. };
  97. detectSound();
  98. };
  99. const transcribeHandler = async (audioBlob) => {
  100. // Create a blob from the audio chunks
  101. await tick();
  102. const file = blobToFile(audioBlob, 'recording.wav');
  103. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  104. toast.error(error);
  105. return null;
  106. });
  107. if (res) {
  108. console.log(res.text);
  109. dispatch('confirm', res.text);
  110. }
  111. };
  112. const saveRecording = (blob) => {
  113. const url = URL.createObjectURL(blob);
  114. const a = document.createElement('a');
  115. document.body.appendChild(a);
  116. a.style = 'display: none';
  117. a.href = url;
  118. a.download = 'recording.wav';
  119. a.click();
  120. window.URL.revokeObjectURL(url);
  121. };
  122. const startRecording = async () => {
  123. startDurationCounter();
  124. stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  125. mediaRecorder = new MediaRecorder(stream);
  126. mediaRecorder.onstart = () => {
  127. console.log('Recording started');
  128. audioChunks = [];
  129. analyseAudio(stream);
  130. };
  131. mediaRecorder.ondataavailable = (event) => audioChunks.push(event.data);
  132. mediaRecorder.onstop = async () => {
  133. console.log('Recording stopped');
  134. if (($settings?.audio?.stt?.engine ?? '') === 'web') {
  135. audioChunks = [];
  136. } else {
  137. if (confirmed) {
  138. const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
  139. await transcribeHandler(audioBlob);
  140. confirmed = false;
  141. loading = false;
  142. }
  143. audioChunks = [];
  144. recording = false;
  145. }
  146. };
  147. mediaRecorder.start();
  148. if ($config.audio.stt.engine === 'web' || ($settings?.audio?.stt?.engine ?? '') === 'web') {
  149. if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
  150. // Create a SpeechRecognition object
  151. speechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  152. // Set continuous to true for continuous recognition
  153. speechRecognition.continuous = true;
  154. // Set the timeout for turning off the recognition after inactivity (in milliseconds)
  155. const inactivityTimeout = 2000; // 3 seconds
  156. let timeoutId;
  157. // Start recognition
  158. speechRecognition.start();
  159. // Event triggered when speech is recognized
  160. speechRecognition.onresult = async (event) => {
  161. // Clear the inactivity timeout
  162. clearTimeout(timeoutId);
  163. // Handle recognized speech
  164. console.log(event);
  165. const transcript = event.results[Object.keys(event.results).length - 1][0].transcript;
  166. transcription = `${transcription}${transcript}`;
  167. await tick();
  168. document.getElementById('chat-input')?.focus();
  169. // Restart the inactivity timeout
  170. timeoutId = setTimeout(() => {
  171. console.log('Speech recognition turned off due to inactivity.');
  172. speechRecognition.stop();
  173. }, inactivityTimeout);
  174. };
  175. // Event triggered when recognition is ended
  176. speechRecognition.onend = function () {
  177. // Restart recognition after it ends
  178. console.log('recognition ended');
  179. confirmRecording();
  180. dispatch('confirm', transcription);
  181. confirmed = false;
  182. loading = false;
  183. };
  184. // Event triggered when an error occurs
  185. speechRecognition.onerror = function (event) {
  186. console.log(event);
  187. toast.error($i18n.t(`Speech recognition error: {{error}}`, { error: event.error }));
  188. dispatch('cancel');
  189. stopRecording();
  190. };
  191. }
  192. }
  193. };
  194. const stopRecording = async () => {
  195. if (recording && mediaRecorder) {
  196. await mediaRecorder.stop();
  197. }
  198. stopDurationCounter();
  199. audioChunks = [];
  200. if (stream) {
  201. const tracks = stream.getTracks();
  202. tracks.forEach((track) => track.stop());
  203. }
  204. stream = null;
  205. };
  206. const confirmRecording = async () => {
  207. loading = true;
  208. confirmed = true;
  209. if (recording && mediaRecorder) {
  210. await mediaRecorder.stop();
  211. }
  212. clearInterval(durationCounter);
  213. if (stream) {
  214. const tracks = stream.getTracks();
  215. tracks.forEach((track) => track.stop());
  216. }
  217. stream = null;
  218. };
  219. </script>
  220. <div
  221. class="{loading
  222. ? ' bg-gray-100/50 dark:bg-gray-850/50'
  223. : 'bg-indigo-300/10 dark:bg-indigo-500/10 '} rounded-full flex {className}"
  224. >
  225. <div class="flex items-center mr-1">
  226. <button
  227. type="button"
  228. class="p-1.5
  229. {loading
  230. ? ' bg-gray-200 dark:bg-gray-700/50'
  231. : 'bg-indigo-400/20 text-indigo-600 dark:text-indigo-300 '}
  232. rounded-full"
  233. on:click={async () => {
  234. dispatch('cancel');
  235. stopRecording();
  236. }}
  237. >
  238. <svg
  239. xmlns="http://www.w3.org/2000/svg"
  240. fill="none"
  241. viewBox="0 0 24 24"
  242. stroke-width="3"
  243. stroke="currentColor"
  244. class="size-4"
  245. >
  246. <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
  247. </svg>
  248. </button>
  249. </div>
  250. <div
  251. class="flex flex-1 self-center items-center justify-between ml-2 mx-1 overflow-hidden h-6"
  252. dir="rtl"
  253. >
  254. <div class="flex-1 flex items-center gap-0.5 h-6">
  255. {#each visualizerData.slice().reverse() as rms}
  256. <div
  257. class="w-[2px]
  258. {loading
  259. ? ' bg-gray-500 dark:bg-gray-400 '
  260. : 'bg-indigo-500 dark:bg-indigo-400 '}
  261. inline-block h-full"
  262. style="height: {Math.min(100, Math.max(14, rms * 100))}%;"
  263. />
  264. {/each}
  265. </div>
  266. </div>
  267. <div class=" mx-1.5 pr-1 flex justify-center items-center">
  268. <div
  269. class="text-sm
  270. {loading ? ' text-gray-500 dark:text-gray-400 ' : ' text-indigo-400 '}
  271. font-medium flex-1 mx-auto text-center"
  272. >
  273. {formatSeconds(durationSeconds)}
  274. </div>
  275. </div>
  276. <div class="flex items-center mr-1">
  277. {#if loading}
  278. <div class=" text-gray-500 rounded-full cursor-not-allowed">
  279. <svg
  280. width="24"
  281. height="24"
  282. viewBox="0 0 24 24"
  283. xmlns="http://www.w3.org/2000/svg"
  284. fill="currentColor"
  285. ><style>
  286. .spinner_OSmW {
  287. transform-origin: center;
  288. animation: spinner_T6mA 0.75s step-end infinite;
  289. }
  290. @keyframes spinner_T6mA {
  291. 8.3% {
  292. transform: rotate(30deg);
  293. }
  294. 16.6% {
  295. transform: rotate(60deg);
  296. }
  297. 25% {
  298. transform: rotate(90deg);
  299. }
  300. 33.3% {
  301. transform: rotate(120deg);
  302. }
  303. 41.6% {
  304. transform: rotate(150deg);
  305. }
  306. 50% {
  307. transform: rotate(180deg);
  308. }
  309. 58.3% {
  310. transform: rotate(210deg);
  311. }
  312. 66.6% {
  313. transform: rotate(240deg);
  314. }
  315. 75% {
  316. transform: rotate(270deg);
  317. }
  318. 83.3% {
  319. transform: rotate(300deg);
  320. }
  321. 91.6% {
  322. transform: rotate(330deg);
  323. }
  324. 100% {
  325. transform: rotate(360deg);
  326. }
  327. }
  328. </style><g class="spinner_OSmW"
  329. ><rect x="11" y="1" width="2" height="5" opacity=".14" /><rect
  330. x="11"
  331. y="1"
  332. width="2"
  333. height="5"
  334. transform="rotate(30 12 12)"
  335. opacity=".29"
  336. /><rect
  337. x="11"
  338. y="1"
  339. width="2"
  340. height="5"
  341. transform="rotate(60 12 12)"
  342. opacity=".43"
  343. /><rect
  344. x="11"
  345. y="1"
  346. width="2"
  347. height="5"
  348. transform="rotate(90 12 12)"
  349. opacity=".57"
  350. /><rect
  351. x="11"
  352. y="1"
  353. width="2"
  354. height="5"
  355. transform="rotate(120 12 12)"
  356. opacity=".71"
  357. /><rect
  358. x="11"
  359. y="1"
  360. width="2"
  361. height="5"
  362. transform="rotate(150 12 12)"
  363. opacity=".86"
  364. /><rect x="11" y="1" width="2" height="5" transform="rotate(180 12 12)" /></g
  365. ></svg
  366. >
  367. </div>
  368. {:else}
  369. <button
  370. type="button"
  371. class="p-1.5 bg-indigo-500 text-white dark:bg-indigo-500 dark:text-blue-950 rounded-full"
  372. on:click={async () => {
  373. await confirmRecording();
  374. }}
  375. >
  376. <svg
  377. xmlns="http://www.w3.org/2000/svg"
  378. fill="none"
  379. viewBox="0 0 24 24"
  380. stroke-width="2.5"
  381. stroke="currentColor"
  382. class="size-4"
  383. >
  384. <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
  385. </svg>
  386. </button>
  387. {/if}
  388. </div>
  389. </div>
  390. <style>
  391. .visualizer {
  392. display: flex;
  393. height: 100%;
  394. }
  395. .visualizer-bar {
  396. width: 2px;
  397. background-color: #4a5aba; /* or whatever color you need */
  398. }
  399. </style>