前端
This commit is contained in:
87
frontend/hooks/web/useVoiceText.ts
Normal file
87
frontend/hooks/web/useVoiceText.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import CommonService from '@/api/common'
|
||||
import type { AudioItem, TranscriptionResult } from '@/src/types/global'
|
||||
|
||||
/**
|
||||
* 转录数据接口
|
||||
*/
|
||||
interface TranscriptionData {
|
||||
file_url?: string
|
||||
transcripts?: Array<{ text: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应结果接口
|
||||
*/
|
||||
interface TranscriptionResponse {
|
||||
results: Array<{
|
||||
transcription_url: string
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* 将音频列表转换为文本转录
|
||||
* @param list - 音频项列表
|
||||
* @returns 转录结果数组
|
||||
* @throws 当转录过程出错时抛出错误
|
||||
*
|
||||
* @example
|
||||
* const audioList = [{ audio_url: 'https://example.com/audio.mp3' }]
|
||||
* const transcriptions = await getVoiceText(audioList)
|
||||
* console.log(transcriptions) // [{ key: 'url', value: 'transcribed text' }]
|
||||
*/
|
||||
export async function getVoiceText(list: AudioItem[]): Promise<TranscriptionResult[]> {
|
||||
// 调用API将视频转换为文本
|
||||
const ret = await CommonService.videoToCharacters({
|
||||
fileLinkList: list.map(item => item.audio_url),
|
||||
})
|
||||
|
||||
// 解析响应数据
|
||||
const data: string = ret.data
|
||||
const rst: TranscriptionResponse = JSON.parse(data)
|
||||
const transcription_url: string[] = rst.results.map(item => item.transcription_url)
|
||||
|
||||
// 并行获取所有转录内容
|
||||
const transcriptions: TranscriptionResult[] = await Promise.all(
|
||||
(transcription_url || []).filter(Boolean).map(async (url: string): Promise<TranscriptionResult> => {
|
||||
try {
|
||||
const resp: Response = await fetch(url)
|
||||
const contentType: string = resp.headers.get('content-type') || ''
|
||||
const value: string = contentType.includes('application/json')
|
||||
? JSON.stringify(await resp.json())
|
||||
: await resp.text()
|
||||
const parsed: TranscriptionData = JSON.parse(value)
|
||||
return {
|
||||
key: url,
|
||||
audio_url: parsed.file_url,
|
||||
value: parsed.transcripts?.[0]?.text || ''
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
console.warn('获取转写内容失败:', url, e)
|
||||
return { key: url, value: '' }
|
||||
}
|
||||
})
|
||||
)
|
||||
return transcriptions
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 返回值接口
|
||||
*/
|
||||
interface UseVoiceTextReturn {
|
||||
getVoiceText: (list: AudioItem[]) => Promise<TranscriptionResult[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* 语音文本转换 Hook
|
||||
* @returns 包含 getVoiceText 方法的对象
|
||||
*
|
||||
* @example
|
||||
* const { getVoiceText } = useVoiceText()
|
||||
* const result = await getVoiceText(audioList)
|
||||
*/
|
||||
export default function useVoiceText(): UseVoiceTextReturn {
|
||||
return { getVoiceText }
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user