Commit 094401cf by liimin

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

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

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