Commit 094401cf by liimin

refactor(components): 重构聊天组件和语音输入组件

- 聊天组件:
  - 优化了代码结构,提高了可读性和可维护性
  - 使用 immer 的 produce 函数优化了状态更新逻辑
  - 调整了部分变量命名,使其更加清晰
  - 移除了未使用的导入和变量

- 语音输入组件:
  - 还原了语音输入组件
1 parent 9b439533
......@@ -7,4 +7,4 @@
background: linear-gradient(91.92deg, #104AE1 -1.74%, #0098EE 75.74%);
background-clip: text;
color: transparent;
}
\ No newline at end of file
}
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useParams, usePathname } from 'next/navigation'
import { RiCloseLine, RiLoader2Line } from '@remixicon/react'
import {
RiCloseLine,
RiLoader2Line,
} from '@remixicon/react'
import Recorder from 'js-audio-recorder'
import { useRafInterval } from 'ahooks'
import { convertToMp3 } from './utils'
......@@ -9,7 +12,6 @@ import s from './index.module.css'
import cn from '@/utils/classnames'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { audioToText } from '@/service/share'
import { set } from 'immer/dist/internal'
type VoiceInputTypes = {
onConverted: (text: string) => void
......@@ -17,17 +19,18 @@ type VoiceInputTypes = {
wordTimestamps?: string
}
const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes) => {
const VoiceInput = ({
onCancel,
onConverted,
wordTimestamps,
}: VoiceInputTypes) => {
const { t } = useTranslation()
// const recorder = useRef(
// new Recorder({
// sampleBits: 16,
// sampleRate: 16000,
// numChannels: 1,
// compiling: false,
// }),
// )
const recorder = useRef(new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
compiling: false,
}))
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const ctxRef = useRef<CanvasRenderingContext2D | null>(null)
const drawRecordId = useRef<number | null>(null)
......@@ -39,13 +42,12 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
const clearInterval = useRafInterval(() => {
setOriginDuration(originDuration + 1)
}, 1000)
const [recorder, setRecorder] = useState<Recorder | null>(null)
const drawRecord = useCallback(() => {
if (!recorder) return
drawRecordId.current = requestAnimationFrame(drawRecord)
const canvas = canvasRef.current!
const ctx = ctxRef.current!
const dataUnit8Array = recorder.getRecordAnalyseData()
const dataUnit8Array = recorder.current.getRecordAnalyseData()
const dataArray = [].slice.call(dataUnit8Array)
const lineLength = Number.parseInt(`${canvas.width / 3}`)
const gap = Number.parseInt(`${1024 / lineLength}`)
......@@ -54,42 +56,37 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
ctx.beginPath()
let x = 0
for (let i = 0; i < lineLength; i++) {
let v =
dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => {
return prev + next
}, 0) / gap
let v = dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => {
return prev + next
}, 0) / gap
if (v < 128) v = 128
if (v > 178) v = 178
const y = ((v - 128) / 50) * canvas.height
if (v < 128)
v = 128
if (v > 178)
v = 178
const y = (v - 128) / 50 * canvas.height
ctx.moveTo(x, 16)
if (ctx.roundRect) ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0])
else ctx.rect(x, 16 - y, 2, y)
if (ctx.roundRect)
ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0])
else
ctx.rect(x, 16 - y, 2, y)
ctx.fill()
x += 3
}
ctx.closePath()
}, [])
const handleStopRecorder = useCallback(async () => {
if (!recorder) return
clearInterval()
recorder.stop()
setStartRecord(false)
setStartConvert(true)
setOriginDuration(0)
recorder.current.stop()
drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
drawRecordId.current = null
const canvas = canvasRef.current!
const ctx = ctxRef.current!
ctx.clearRect(0, 0, canvas.width, canvas.height)
const mp3Blob = convertToMp3(recorder)
if (!mp3Blob.size) {
console.error('音频数据为空')
onConverted('')
onCancel()
return
}
const mp3Blob = convertToMp3(recorder.current)
const mp3File = new File([mp3Blob], 'temp.mp3', { type: 'audio/mp3' })
const formData = new FormData()
formData.append('file', mp3File)
......@@ -101,42 +98,34 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
if (params.token) {
url = '/audio-to-text'
isPublic = true
} else if (params.appId) {
if (pathname.search('explore/installed') > -1) url = `/installed-apps/${params.appId}/audio-to-text`
else url = `/apps/${params.appId}/audio-to-text`
}
else if (params.appId) {
if (pathname.search('explore/installed') > -1)
url = `/installed-apps/${params.appId}/audio-to-text`
else
url = `/apps/${params.appId}/audio-to-text`
}
try {
const audioResponse = await audioToText(url, isPublic, formData)
onConverted(audioResponse.text)
onCancel()
} catch {
}
catch {
onConverted('')
onCancel()
}
}, [clearInterval, onCancel, onConverted, params.appId, params.token, pathname, wordTimestamps])
const handleStartRecord = async () => {
try {
if (recorder) {
recorder.stop()
setRecorder(null)
}
const newRecorder = new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
compiling: false,
})
await newRecorder.start()
setRecorder(newRecorder)
await recorder.current.start()
setStartRecord(true)
setStartConvert(false)
if (canvasRef.current && ctxRef.current)
requestAnimationFrame(() => {
drawRecord()
})
} catch {
drawRecord()
}
catch {
onCancel()
}
}
......@@ -160,29 +149,15 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
}
}
}
if (originDuration >= 600 && startRecord) handleStopRecorder()
if (originDuration >= 600 && startRecord)
handleStopRecorder()
useEffect(() => {
initCanvas()
const startRecording = async () => {
try {
await handleStartRecord()
} catch (error) {
console.error('自动录音失败:', error)
onCancel()
}
}
startRecording()
// const recorderRef = recorder?.current
handleStartRecord()
const recorderRef = recorder?.current
return () => {
recorder?.stop()
recorder?.destroy()
setRecorder(null)
clearInterval()
if (drawRecordId.current) {
cancelAnimationFrame(drawRecordId.current)
}
recorderRef?.stop()
}
}, [])
......@@ -191,23 +166,47 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
return (
<div className={cn(s.wrapper, 'absolute inset-0 rounded-xl')}>
<div className="absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 py-[14px] pl-[14.5px] pr-[6.5px]">
<canvas id="voice-input-record" className="absolute bottom-0 left-0 h-4 w-full" />
{startConvert && <RiLoader2Line className="mr-2 h-4 w-4 animate-spin text-primary-700" />}
<div className="grow">
{startRecord && <div className="text-sm text-gray-500">{t('common.voiceInput.speaking')}</div>}
{startConvert && <div className={cn(s.convert, 'text-sm')}>{t('common.voiceInput.converting')}</div>}
<div className='absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 py-[14px] pl-[14.5px] pr-[6.5px]'>
<canvas id='voice-input-record' className='absolute bottom-0 left-0 h-4 w-full' />
{
startConvert && <RiLoader2Line className='mr-2 h-4 w-4 animate-spin text-primary-700' />
}
<div className='grow'>
{
startRecord && (
<div className='text-sm text-gray-500'>
{t('common.voiceInput.speaking')}
</div>
)
}
{
startConvert && (
<div className={cn(s.convert, 'text-sm')}>
{t('common.voiceInput.converting')}
</div>
)
}
</div>
{startRecord && (
<div className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100" onClick={handleStopRecorder}>
<StopCircle className="h-5 w-5 text-primary-600" />
</div>
)}
{startConvert && (
<div className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-gray-200" onClick={onCancel}>
<RiCloseLine className="h-4 w-4 text-gray-500" />
</div>
)}
{
startRecord && (
<div
className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100'
onClick={handleStopRecorder}
>
<StopCircle className='h-5 w-5 text-primary-600' />
</div>
)
}
{
startConvert && (
<div
className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-gray-200'
onClick={onCancel}
>
<RiCloseLine className='h-4 w-4 text-gray-500' />
</div>
)
}
<div className={`w-[45px] pl-1 text-xs font-medium ${originDuration > 500 ? 'text-[#F04438]' : 'text-gray-700'}`}>{`0${minutes.toFixed(0)}:${seconds >= 10 ? seconds : `0${seconds}`}`}</div>
</div>
</div>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!