67 lines
1.5 KiB
TypeScript
67 lines
1.5 KiB
TypeScript
/**
|
|
* 字幕数据类型定义和处理工具
|
|
*/
|
|
|
|
export interface WordTimestamp {
|
|
word: string;
|
|
start: number;
|
|
end: number;
|
|
}
|
|
|
|
export interface Segment {
|
|
text: string;
|
|
start: number;
|
|
end: number;
|
|
words: WordTimestamp[];
|
|
}
|
|
|
|
export interface CaptionsData {
|
|
segments: Segment[];
|
|
}
|
|
|
|
/**
|
|
* 根据当前时间获取应该显示的字幕段落
|
|
*/
|
|
export function getCurrentSegment(
|
|
captions: CaptionsData,
|
|
currentTimeInSeconds: number
|
|
): Segment | null {
|
|
for (const segment of captions.segments) {
|
|
if (currentTimeInSeconds >= segment.start && currentTimeInSeconds <= segment.end) {
|
|
return segment;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* 根据当前时间获取当前高亮的字的索引
|
|
*/
|
|
export function getCurrentWordIndex(
|
|
segment: Segment,
|
|
currentTimeInSeconds: number
|
|
): number {
|
|
for (let i = 0; i < segment.words.length; i++) {
|
|
const word = segment.words[i];
|
|
if (currentTimeInSeconds >= word.start && currentTimeInSeconds <= word.end) {
|
|
return i;
|
|
}
|
|
// 如果当前时间在两个字之间,返回前一个字
|
|
if (i < segment.words.length - 1) {
|
|
const nextWord = segment.words[i + 1];
|
|
if (currentTimeInSeconds > word.end && currentTimeInSeconds < nextWord.start) {
|
|
return i;
|
|
}
|
|
}
|
|
}
|
|
// 如果超过最后一个字的结束时间,返回最后一个字
|
|
if (segment.words.length > 0) {
|
|
const lastWord = segment.words[segment.words.length - 1];
|
|
if (currentTimeInSeconds >= lastWord.end) {
|
|
return segment.words.length - 1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|