index.tsx
7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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 Recorder from 'js-audio-recorder'
import { useRafInterval } from 'ahooks'
import { convertToMp3 } from './utils'
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'
type VoiceInputTypes = {
onConverted: (text: string) => void
onCancel: () => void
wordTimestamps?: string
}
const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes) => {
const { t } = useTranslation()
// 修改点1: 使用ref保存Recorder实例
const recorder = useRef<Recorder | null>(null)
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const ctxRef = useRef<CanvasRenderingContext2D | null>(null)
const drawRecordId = useRef<number | null>(null)
const [originDuration, setOriginDuration] = useState(0)
// const [startRecord, setStartRecord] = useState(false)
// const [startConvert, setStartConvert] = useState(false)
const [statement, setStatement] = useState<'recording' | 'converting' | 'none'>('none')
const pathname = usePathname()
const params = useParams()
const clearInterval = useRafInterval(() => {
setOriginDuration(originDuration + 1)
}, 1000)
// 修改点2: 创建新的Recorder实例
const createRecorder = () => {
return new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
compiling: false,
})
}
const drawRecord = useCallback(() => {
if (!recorder.current) return
drawRecordId.current = requestAnimationFrame(drawRecord)
const canvas = canvasRef.current!
const ctx = ctxRef.current!
const dataUnit8Array = recorder.current.getRecordAnalyseData()
const dataArray = [].slice.call(dataUnit8Array)
const lineLength = Number.parseInt(`${canvas.width / 3}`)
const gap = Number.parseInt(`${1024 / lineLength}`)
ctx.clearRect(0, 0, canvas.width, canvas.height)
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
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)
ctx.fill()
x += 3
}
ctx.closePath()
}, [])
const handleStopRecorder = useCallback(async () => {
clearInterval()
if (recorder.current) {
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.current)
const mp3File = new File([mp3Blob], 'temp.mp3', { type: 'audio/mp3' })
const formData = new FormData()
formData.append('file', mp3File)
formData.append('word_timestamps', wordTimestamps || 'disabled')
let url = ''
let isPublic = false
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`
}
try {
const audioResponse = await audioToText(url, isPublic, formData)
onConverted(audioResponse.text)
} catch (e) {
onConverted('')
} finally {
setStatement('none')
onCancel()
}
}
}, [clearInterval, onCancel, onConverted, params.appId, params.token, pathname, wordTimestamps])
const handleStop = useCallback(() => {
setStatement('converting')
setTimeout(handleStopRecorder, 0)
}, [handleStopRecorder])
const handleStartRecord = async () => {
try {
resetRecorder()
recorder.current = createRecorder()
await recorder.current.start()
setStatement('recording')
setTimeout(() => {
setOriginDuration(0) // 重置录音时间
initCanvas()
drawRecord()
}, 0)
} catch (e: any) {
onCancel()
}
}
const initCanvas = () => {
const dpr = window.devicePixelRatio || 1
const canvas = document.getElementById('voice-input-record') as HTMLCanvasElement
const { width: cssWidth, height: cssHeight } = canvas.getBoundingClientRect()
canvas.width = dpr * cssWidth
canvas.height = dpr * cssHeight
canvasRef.current = canvas
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.scale(dpr, dpr)
ctx.fillStyle = 'rgba(30, 144, 255, 1)'
ctxRef.current = ctx
} else {
console.error('Failed to get canvas context')
}
}
// 修改点6: 添加录音超时处理
useEffect(() => {
if (originDuration >= 600 && statement === 'recording') {
handleStop()
}
}, [originDuration, statement, handleStop])
useEffect(() => {
handleStartRecord()
return () => {
resetRecorder()
drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
clearInterval()
}
}, [])
const resetRecorder = useCallback(() => {
if (recorder.current) {
recorder.current.stop()
recorder.current.destroy()
recorder.current = null
}
}, [])
const minutes = Math.floor(originDuration / 60)
const seconds = originDuration % 60
return (
<div className={cn(s.wrapper, 'absolute inset-0 rounded-xl z-10')}>
{/* <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> */}
<div className="absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 pl-[14.5px] pr-[6.5px]">
<canvas id="voice-input-record" className="absolute bottom-0 left-0 h-4 w-full" />
{statement === 'converting' && <RiLoader2Line className="mr-2 h-4 w-4 animate-spin text-primary-700" />}
<div className="grow">
{statement === 'recording' && <div className="text-sm text-gray-500">{t('common.voiceInput.speaking')}</div>}
{statement === 'converting' && (
<div className={cn(s.convert, 'text-sm')}>{t('common.voiceInput.converting')}</div>
)}
</div>
{statement === 'recording' && (
<div
className="mr-1 flex h-10 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100"
onClick={handleStop}>
<StopCircle className="h-5 w-5 text-primary-600" />
</div>
)}
{/* {statement==='converting' && (
<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'}`}>
{`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`}
</div>
</div>
</div>
)
}
export default VoiceInput