Files
sionrui/frontend/hooks/web/useVoiceText.ts

83 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-11-12 22:45:29 +08:00
// 使用公共类型定义
import type {
AudioItem,
TranscriptionResult,
TranscriptionResponse,
TranscriptionData
} from '@gold/config/types'
2025-11-10 00:59:40 +08:00
2025-11-13 01:06:28 +08:00
// 直接导入 TikHub 服务,无需全局注入
import { TikHubService } from '@gold/api/services'
2025-11-10 00:59:40 +08:00
/**
*
* @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' }]
*/
2025-11-12 22:45:29 +08:00
export async function getVoiceText(
2025-11-13 01:06:28 +08:00
list: AudioItem[]
2025-11-12 22:45:29 +08:00
): Promise<TranscriptionResult[]> {
2025-11-13 01:06:28 +08:00
// 直接使用 TikHub 服务
const ret = await TikHubService.videoToCharacters({
2025-11-10 00:59:40 +08:00
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 {
2025-11-13 01:06:28 +08:00
getVoiceText: (list: AudioItem[]) => Promise<TranscriptionResult[]>
2025-11-10 00:59:40 +08:00
}
/**
* Hook
* @returns getVoiceText
*
* @example
* const { getVoiceText } = useVoiceText()
* const result = await getVoiceText(audioList)
*/
2025-11-13 01:06:28 +08:00
export default function useVoiceText(): UseVoiceTextReturn {
2025-11-12 22:45:29 +08:00
return {
2025-11-13 01:06:28 +08:00
getVoiceText
2025-11-12 22:45:29 +08:00
}
2025-11-10 00:59:40 +08:00
}