83 lines
2.3 KiB
TypeScript
83 lines
2.3 KiB
TypeScript
// 使用公共类型定义
|
|
import type {
|
|
AudioItem,
|
|
TranscriptionResult,
|
|
TranscriptionResponse,
|
|
TranscriptionData
|
|
} from '@gold/config/types'
|
|
|
|
// 直接导入 TikHub 服务,无需全局注入
|
|
import { TikHubService } from '@gold/api/services'
|
|
|
|
/**
|
|
* 将音频列表转换为文本转录
|
|
* @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[]> {
|
|
// 直接使用 TikHub 服务
|
|
const ret = await TikHubService.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
|
|
}
|
|
}
|
|
|
|
|
|
|