index.tsx 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { useCallback, useEffect, useRef, useState } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { useParams, usePathname } from 'next/navigation'
  4. import cn from 'classnames'
  5. import Recorder from 'js-audio-recorder'
  6. import { useRafInterval } from 'ahooks'
  7. import s from './index.module.css'
  8. import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
  9. import { Loading02, XClose } from '@/app/components/base/icons/src/vender/line/general'
  10. import { audioToText } from '@/service/share'
  11. type VoiceInputTypes = {
  12. onConverted: (text: string) => void
  13. onCancel: () => void
  14. }
  15. const VoiceInput = ({
  16. onCancel,
  17. onConverted,
  18. }: VoiceInputTypes) => {
  19. const { t } = useTranslation()
  20. const recorder = useRef(new Recorder())
  21. const canvasRef = useRef<HTMLCanvasElement | null>(null)
  22. const ctxRef = useRef<CanvasRenderingContext2D | null>(null)
  23. const drawRecordId = useRef<number | null>(null)
  24. const [originDuration, setOriginDuration] = useState(0)
  25. const [startRecord, setStartRecord] = useState(false)
  26. const [startConvert, setStartConvert] = useState(false)
  27. const pathname = usePathname()
  28. const params = useParams()
  29. const clearInterval = useRafInterval(() => {
  30. setOriginDuration(originDuration + 1)
  31. }, 1000)
  32. const drawRecord = useCallback(() => {
  33. drawRecordId.current = requestAnimationFrame(drawRecord)
  34. const canvas = canvasRef.current!
  35. const ctx = ctxRef.current!
  36. const dataUnit8Array = recorder.current.getRecordAnalyseData()
  37. const dataArray = [].slice.call(dataUnit8Array)
  38. const lineLength = parseInt(`${canvas.width / 3}`)
  39. const gap = parseInt(`${1024 / lineLength}`)
  40. ctx.clearRect(0, 0, canvas.width, canvas.height)
  41. ctx.beginPath()
  42. let x = 0
  43. for (let i = 0; i < lineLength; i++) {
  44. let v = dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => {
  45. return prev + next
  46. }, 0) / gap
  47. if (v < 128)
  48. v = 128
  49. if (v > 178)
  50. v = 178
  51. const y = (v - 128) / 50 * canvas.height
  52. ctx.moveTo(x, 16)
  53. ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0])
  54. ctx.fill()
  55. x += 3
  56. }
  57. ctx.closePath()
  58. }, [])
  59. const handleStopRecorder = useCallback(async () => {
  60. clearInterval()
  61. setStartRecord(false)
  62. setStartConvert(true)
  63. recorder.current.stop()
  64. drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
  65. drawRecordId.current = null
  66. const canvas = canvasRef.current!
  67. const ctx = ctxRef.current!
  68. ctx.clearRect(0, 0, canvas.width, canvas.height)
  69. const wavBlob = recorder.current.getWAVBlob()
  70. const wavFile = new File([wavBlob], 'a.wav', { type: 'audio/wav' })
  71. const formData = new FormData()
  72. formData.append('file', wavFile)
  73. let url = ''
  74. let isPublic = false
  75. if (params.token) {
  76. url = '/audio-to-text'
  77. isPublic = true
  78. }
  79. else if (params.appId) {
  80. if (pathname.search('explore/installed') > -1)
  81. url = `/installed-apps/${params.appId}/audio-to-text`
  82. else
  83. url = `/apps/${params.appId}/audio-to-text`
  84. }
  85. try {
  86. const audioResponse = await audioToText(url, isPublic, formData)
  87. onConverted(audioResponse.text)
  88. onCancel()
  89. }
  90. catch (e) {
  91. onConverted('')
  92. onCancel()
  93. }
  94. }, [])
  95. const handleStartRecord = async () => {
  96. try {
  97. await recorder.current.start()
  98. setStartRecord(true)
  99. setStartConvert(false)
  100. if (canvasRef.current && ctxRef.current)
  101. drawRecord()
  102. }
  103. catch (e) {
  104. onCancel()
  105. }
  106. }
  107. const initCanvas = () => {
  108. const dpr = window.devicePixelRatio || 1
  109. const canvas = document.getElementById('voice-input-record') as HTMLCanvasElement
  110. if (canvas) {
  111. const { width: cssWidth, height: cssHeight } = canvas.getBoundingClientRect()
  112. canvas.width = dpr * cssWidth
  113. canvas.height = dpr * cssHeight
  114. canvasRef.current = canvas
  115. const ctx = canvas.getContext('2d')
  116. if (ctx) {
  117. ctx.scale(dpr, dpr)
  118. ctx.fillStyle = 'rgba(209, 224, 255, 1)'
  119. ctxRef.current = ctx
  120. }
  121. }
  122. }
  123. if (originDuration >= 120 && startRecord)
  124. handleStopRecorder()
  125. useEffect(() => {
  126. initCanvas()
  127. handleStartRecord()
  128. }, [])
  129. const minutes = parseInt(`${parseInt(`${originDuration}`) / 60}`)
  130. const seconds = parseInt(`${originDuration}`) % 60
  131. return (
  132. <div className={cn(s.wrapper, 'absolute inset-0 rounded-xl')}>
  133. <div className='absolute inset-[1.5px] flex items-center pl-[14.5px] pr-[6.5px] py-[14px] bg-primary-25 rounded-[10.5px] overflow-hidden'>
  134. <canvas id='voice-input-record' className='absolute left-0 bottom-0 w-full h-4' />
  135. {
  136. startConvert && <Loading02 className='animate-spin mr-2 w-4 h-4 text-primary-700' />
  137. }
  138. <div className='grow'>
  139. {
  140. startRecord && (
  141. <div className='text-sm text-gray-500'>
  142. {t('common.voiceInput.speaking')}
  143. </div>
  144. )
  145. }
  146. {
  147. startConvert && (
  148. <div className={cn(s.convert, 'text-sm')}>
  149. {t('common.voiceInput.converting')}
  150. </div>
  151. )
  152. }
  153. </div>
  154. {
  155. startRecord && (
  156. <div
  157. className='flex justify-center items-center mr-1 w-8 h-8 hover:bg-primary-100 rounded-lg cursor-pointer'
  158. onClick={handleStopRecorder}
  159. >
  160. <StopCircle className='w-5 h-5 text-primary-600' />
  161. </div>
  162. )
  163. }
  164. {
  165. startConvert && (
  166. <div
  167. className='flex justify-center items-center mr-1 w-8 h-8 hover:bg-gray-200 rounded-lg cursor-pointer'
  168. onClick={onCancel}
  169. >
  170. <XClose className='w-4 h-4 text-gray-500' />
  171. </div>
  172. )
  173. }
  174. <div className={`w-[45px] pl-1 text-xs font-medium ${originDuration > 110 ? 'text-[#F04438]' : 'text-gray-700'}`}>{`0${minutes.toFixed(0)}:${seconds >= 10 ? seconds : `0${seconds}`}`}</div>
  175. </div>
  176. </div>
  177. )
  178. }
  179. export default VoiceInput