Commit b75fd32d by liimin

refactor(voice-input): 优化语音输入组件的录音和转换逻辑

- 使用 ref 保存 Recorder 实例,确保安全访问和释放资源
- 添加创建新 Recorder 实例的方法,避免重复使用旧实例
- 优化录音开始和停止逻辑,解决切换 tab 时继续录音的问题
- 添加录音超时处理,自动停止长时间录音
- 调整录音时间显示格式,统一分钟和秒数格式化
- 优化组件渲染,提高代码可读性和维护性
1 parent 094401cf
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 { import { RiCloseLine, RiLoader2Line } from '@remixicon/react'
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'
...@@ -19,18 +16,10 @@ type VoiceInputTypes = { ...@@ -19,18 +16,10 @@ type VoiceInputTypes = {
wordTimestamps?: string wordTimestamps?: string
} }
const VoiceInput = ({ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes) => {
onCancel,
onConverted,
wordTimestamps,
}: VoiceInputTypes) => {
const { t } = useTranslation() const { t } = useTranslation()
const recorder = useRef(new Recorder({ // 修改点1: 使用ref保存Recorder实例
sampleBits: 16, const recorder = useRef<Recorder | null>(null)
sampleRate: 16000,
numChannels: 1,
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)
...@@ -43,7 +32,19 @@ const VoiceInput = ({ ...@@ -43,7 +32,19 @@ const VoiceInput = ({
setOriginDuration(originDuration + 1) setOriginDuration(originDuration + 1)
}, 1000) }, 1000)
// 修改点2: 创建新的Recorder实例
const createRecorder = () => {
return new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
compiling: false,
})
}
const drawRecord = useCallback(() => { const drawRecord = useCallback(() => {
if (!recorder.current) 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!
...@@ -56,36 +57,39 @@ const VoiceInput = ({ ...@@ -56,36 +57,39 @@ const VoiceInput = ({
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 = dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => { let v =
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) if (v < 128) v = 128
v = 128 if (v > 178) v = 178
if (v > 178) const y = ((v - 128) / 50) * canvas.height
v = 178
const y = (v - 128) / 50 * canvas.height
ctx.moveTo(x, 16) ctx.moveTo(x, 16)
if (ctx.roundRect) if (ctx.roundRect) ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0])
ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0]) else ctx.rect(x, 16 - y, 2, y)
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 () => {
clearInterval() clearInterval()
setStartRecord(false) setStartRecord(false)
setStartConvert(true) setStartConvert(true)
// 修改点3: 安全访问recorder实例
if (recorder.current) {
recorder.current.stop() 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.current) const mp3Blob = convertToMp3(recorder.current)
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()
...@@ -98,34 +102,54 @@ const VoiceInput = ({ ...@@ -98,34 +102,54 @@ const VoiceInput = ({
if (params.token) { if (params.token) {
url = '/audio-to-text' url = '/audio-to-text'
isPublic = true isPublic = true
} } else if (params.appId) {
else if (params.appId) { if (pathname.search('explore/installed') > -1) url = `/installed-apps/${params.appId}/audio-to-text`
if (pathname.search('explore/installed') > -1) else url = `/apps/${params.appId}/audio-to-text`
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 (e) {
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 {
// 修改点4: 确保清理之前的录音实例
if (recorder.current) {
try {
if (recorder.current.isRecording) {
await recorder.current.stop()
}
recorder.current.destroy()
} catch (e) {
console.error('Error destroying previous recorder:', e)
}
}
// 创建新的录音实例
recorder.current = createRecorder()
await recorder.current.start() await recorder.current.start()
setStartRecord(true) setStartRecord(true)
setStartConvert(false) setStartConvert(false)
setOriginDuration(0) // 重置录音时间
if (canvasRef.current && ctxRef.current) // 修改点5: 确保canvas正确初始化
initCanvas()
if (canvasRef.current && ctxRef.current) {
drawRecord() drawRecord()
} else {
console.error('Canvas or context not available')
} }
catch { } catch (e: any) {
console.error('Recording start error:', e)
alert(`录音启动失败: ${e.message || '请检查麦克风权限'}`)
onCancel() onCancel()
} }
} }
...@@ -146,68 +170,68 @@ const VoiceInput = ({ ...@@ -146,68 +170,68 @@ const VoiceInput = ({
ctx.scale(dpr, dpr) ctx.scale(dpr, dpr)
ctx.fillStyle = 'rgba(209, 224, 255, 1)' ctx.fillStyle = 'rgba(209, 224, 255, 1)'
ctxRef.current = ctx ctxRef.current = ctx
} else {
console.error('Failed to get canvas context')
} }
} else {
console.error('Canvas element not found')
} }
} }
if (originDuration >= 600 && startRecord)
// 修改点6: 添加录音超时处理
useEffect(() => {
if (originDuration >= 600 && startRecord) {
handleStopRecorder() handleStopRecorder()
}
}, [originDuration, startRecord, handleStopRecorder])
useEffect(() => { useEffect(() => {
initCanvas()
handleStartRecord() handleStartRecord()
const recorderRef = recorder?.current
// 修改点7: 清理函数确保释放资源
return () => { return () => {
recorderRef?.stop() if (recorder.current) {
try {
if (recorder.current.isRecording) {
recorder.current.stop()
}
recorder.current.destroy()
} catch (e) {
console.error('Cleanup error:', e)
}
recorder.current = null
}
drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
clearInterval()
} }
}, []) }, [])
const minutes = Number.parseInt(`${Number.parseInt(`${originDuration}`) / 60}`) const minutes = Math.floor(originDuration / 60)
const seconds = Number.parseInt(`${originDuration}`) % 60 const seconds = originDuration % 60
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" />}
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>}
<div className='grow'> {startConvert && <div className={cn(s.convert, 'text-sm')}>{t('common.voiceInput.converting')}</div>}
{
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>
{ )}
startRecord && ( {startConvert && (
<div <div className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-gray-200" onClick={onCancel}>
className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100' <RiCloseLine className="h-4 w-4 text-gray-500" />
onClick={handleStopRecorder}
>
<StopCircle className='h-5 w-5 text-primary-600' />
</div> </div>
) )}
} <div className={`w-[45px] pl-1 text-xs font-medium ${originDuration > 500 ? 'text-[#F04438]' : 'text-gray-700'}`}>
{ {`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`}
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>
)
}
<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!