Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | /** * 时间计算器 * * @description 计算每个音符的绝对播放时间 * * 核心公式: * - noteLength = realValue * beatUnitRatio * (60 / bpm) * - time = relativeTime + fixtime * - endtime = time + noteLength * * 其中: * - realValue: 音符时值(以四分音符为单位) * - beatUnitRatio: 节拍单位比例(四分音符=1,八分音符=0.5) * - bpm: 每分钟节拍数 * - fixtime: 节拍器前奏时间 */ import { JianpuScore } from '../../models/JianpuScore'; import { JianpuNote } from '../../models/JianpuNote'; import { JianpuMeasure } from '../../models/JianpuMeasure'; // ==================== 常量定义 ==================== /** 默认节拍器拍数 */ const DEFAULT_METRONOME_BEATS = 2; /** 节拍单位到比例的映射 */ const BEAT_UNIT_RATIO: Record<string, number> = { 'whole': 4.0, 'half': 2.0, 'quarter': 1.0, 'eighth': 0.5, '16th': 0.25, '32nd': 0.125, '1/1': 4.0, '1/2': 2.0, '1/4': 1.0, '1/8': 0.5, '1/16': 0.25, '1/32': 0.125, }; // ==================== 类型定义 ==================== /** 时间计算配置 */ export interface TimeCalculatorConfig { /** 是否启用节拍器前奏 */ enableMetronome?: boolean; /** 节拍器拍数(默认2拍) */ metronomeBeatCount?: number; /** 是否处理弱起小节 */ handlePickupMeasure?: boolean; /** 速度单位(默认 '1/4') */ beatUnit?: string; /** 音频播放倍率(默认1.0) */ playbackRate?: number; /** 是否启用调试日志 */ debug?: boolean; } /** 小节速度信息 */ export interface MeasureTempoInfo { /** 小节索引 */ measureIndex: number; /** BPM速度 */ bpm: number; /** 节拍单位 */ beatUnit: string; /** 是否是渐变起点 */ isGradualStart?: boolean; /** 是否是渐变终点 */ isGradualEnd?: boolean; /** 渐变速度数组 */ gradualSpeeds?: number[]; } /** 时间计算结果 */ export interface TimeCalculationResult { /** 是否有弱起 */ hasPickup: boolean; /** 弱起补充时间(秒) */ pickupTime: number; /** 节拍器时间(秒) */ metronomeTime: number; /** 总fixtime(秒) */ fixtime: number; /** 总时长(秒) */ totalDuration: number; /** 小节速度信息 */ tempoMap: MeasureTempoInfo[]; } // ==================== 主类 ==================== /** * 时间计算器 */ export class TimeCalculator { /** 配置 */ private config: Required<Omit<TimeCalculatorConfig, 'debug'>> & { debug: boolean }; /** 计算结果 */ private result: TimeCalculationResult = { hasPickup: false, pickupTime: 0, metronomeTime: 0, fixtime: 0, totalDuration: 0, tempoMap: [], }; /** 日志输出(受debug开关控制) */ private log(...args: any[]): void { if (this.config.debug) { console.log('[TimeCalculator]', ...args); } } /** * 构造函数 * @param config 配置选项 */ constructor(config: TimeCalculatorConfig = {}) { this.config = { enableMetronome: config.enableMetronome ?? false, metronomeBeatCount: config.metronomeBeatCount ?? DEFAULT_METRONOME_BEATS, handlePickupMeasure: config.handlePickupMeasure ?? true, beatUnit: config.beatUnit ?? '1/4', playbackRate: config.playbackRate ?? 1.0, debug: config.debug ?? false, }; } /** * 计算所有音符的绝对时间 * * @param score JianpuScore对象 * @returns 计算结果 */ calculateTimes(score: JianpuScore): TimeCalculationResult { this.log('开始计算音符时间'); const startTime = performance.now(); // 重置结果 this.resetResult(); const { measures, tempo } = score; if (!measures || measures.length === 0) { console.warn('[TimeCalculator] 没有小节数据'); return this.result; } // 1. 构建速度映射表 this.buildTempoMap(measures, tempo); // 2. 计算节拍器时间 if (this.config.enableMetronome) { this.result.metronomeTime = this.calculateMetronomeTime(tempo); } // 3. 检测弱起小节 if (this.config.handlePickupMeasure) { this.result.pickupTime = this.detectPickupMeasure(measures[0], tempo); this.result.hasPickup = this.result.pickupTime > 0; } // 4. 计算总fixtime this.result.fixtime = this.result.metronomeTime + this.result.pickupTime; // 5. 计算每个音符的时间 let cumulativeTime = 0; for (let measureIdx = 0; measureIdx < measures.length; measureIdx++) { const measure = measures[measureIdx]; const tempoInfo = this.getTempoForMeasure(measureIdx, tempo); const bpm = tempoInfo.bpm / this.config.playbackRate; const beatUnitRatio = this.getBeatUnitRatio(tempoInfo.beatUnit); // 计算小节时长 const measureDuration = this.calculateMeasureDuration(measure, bpm, beatUnitRatio); // 遍历所有声部 for (let voiceIdx = 0; voiceIdx < measure.voices.length; voiceIdx++) { const voice = measure.voices[voiceIdx]; // 按时间戳排序 const sortedNotes = [...voice].sort((a, b) => a.timestamp - b.timestamp); for (const note of sortedNotes) { this.calculateNoteTime( note, cumulativeTime, bpm, beatUnitRatio, measureIdx, measureDuration ); } } // 累计小节时间 cumulativeTime += measureDuration; } this.result.totalDuration = cumulativeTime; const elapsed = performance.now() - startTime; this.log(`计算完成,耗时 ${elapsed.toFixed(2)}ms`); return this.result; } /** * 获取计算结果 */ getResult(): TimeCalculationResult { return { ...this.result }; } // ==================== 私有方法 ==================== /** * 重置计算结果 */ private resetResult(): void { this.result = { hasPickup: false, pickupTime: 0, metronomeTime: 0, fixtime: 0, totalDuration: 0, tempoMap: [], }; } /** * 构建速度映射表 */ private buildTempoMap(measures: JianpuMeasure[], defaultTempo: number): void { let currentTempo = defaultTempo; for (let i = 0; i < measures.length; i++) { const measure = measures[i]; // 检查小节是否有速度标记 if (measure.tempo !== undefined) { currentTempo = measure.tempo; } this.result.tempoMap.push({ measureIndex: i, bpm: currentTempo, beatUnit: this.config.beatUnit, }); } } /** * 获取指定小节的速度信息 */ private getTempoForMeasure(measureIndex: number, defaultTempo: number): MeasureTempoInfo { const info = this.result.tempoMap[measureIndex]; if (info) { return info; } return { measureIndex, bpm: defaultTempo, beatUnit: this.config.beatUnit, }; } /** * 计算节拍器时间 */ private calculateMetronomeTime(bpm: number): number { // 每拍时长 = 60 / bpm const beatDuration = 60 / bpm; return beatDuration * this.config.metronomeBeatCount; } /** * 检测弱起小节 */ private detectPickupMeasure(firstMeasure: JianpuMeasure, tempo: number): number { if (!firstMeasure) return 0; const { beats, beatType } = firstMeasure.timeSignature; // 计算小节理论时值(以四分音符为单位) const theoreticalRealValue = beats * (4 / beatType); // 计算实际音符时值 let actualRealValue = 0; for (const voice of firstMeasure.voices) { for (const note of voice) { actualRealValue += note.duration; } // 只检查第一声部 break; } // 如果实际时值小于理论时值,说明是弱起 if (actualRealValue < theoreticalRealValue - 0.001) { const missingRealValue = theoreticalRealValue - actualRealValue; const beatDuration = 60 / tempo; return missingRealValue * beatDuration; } return 0; } /** * 计算小节时长 */ private calculateMeasureDuration( measure: JianpuMeasure, bpm: number, beatUnitRatio: number ): number { const { beats, beatType } = measure.timeSignature; // 小节时值(以四分音符为单位) const measureRealValue = beats * (4 / beatType); // 四分音符时长(秒) const quarterNoteDuration = 60 / bpm; // 小节时长 = 小节时值 * 节拍单位比例 * 四分音符时长 return measureRealValue * beatUnitRatio * quarterNoteDuration; } /** * 计算单个音符的时间 */ private calculateNoteTime( note: JianpuNote, measureStartTime: number, bpm: number, beatUnitRatio: number, measureIndex: number, measureDuration: number ): void { // 四分音符时长(秒) const quarterNoteDuration = 60 / bpm; // 音符时值时长(秒) const noteDuration = note.duration * beatUnitRatio * quarterNoteDuration; // 音符在小节内的相对位置时间 const noteOffsetInMeasure = note.timestamp * beatUnitRatio * quarterNoteDuration; // 相对时间(不含fixtime) const relativeTime = measureStartTime + noteOffsetInMeasure; // 绝对时间(含fixtime) const absoluteTime = relativeTime + this.result.fixtime; // 设置音符时间 note.startTime = absoluteTime; note.endTime = absoluteTime + noteDuration; // 更新OSMD兼容数据 if (note.osmdCompatible) { // 添加兼容字段(如果需要) const compat = note.osmdCompatible as any; compat.time = absoluteTime; compat.endtime = note.endTime; compat.relativeTime = relativeTime; compat.relaEndtime = relativeTime + noteDuration; compat.duration = noteDuration; compat.fixtime = this.result.fixtime; compat.difftime = this.result.pickupTime; compat.measureLength = measureDuration; compat.noteLengthTime = noteDuration; compat._noteLength = note.duration; } } /** * 获取节拍单位比例 */ private getBeatUnitRatio(beatUnit: string): number { const ratio = BEAT_UNIT_RATIO[beatUnit.toLowerCase()]; if (ratio !== undefined) { return ratio; } // 尝试解析 "1/4" 格式 const match = beatUnit.match(/^(\d+)\/(\d+)$/); if (match) { const num = parseInt(match[1]); const den = parseInt(match[2]); return (num / den) * 4; // 转换为以四分音符为基准 } console.warn(`[TimeCalculator] 未知的节拍单位: ${beatUnit},使用默认值1.0`); return 1.0; } /** * 更新配置 */ updateConfig(config: Partial<TimeCalculatorConfig>): void { Object.assign(this.config, config); } /** * 获取当前配置 */ getConfig(): Required<TimeCalculatorConfig> { return { ...this.config }; } } // ==================== 工厂函数 ==================== /** * 创建时间计算器 */ export function createTimeCalculator(config?: TimeCalculatorConfig): TimeCalculator { return new TimeCalculator(config); } // ==================== 工具函数 ==================== /** * 计算节拍器时间 * @param bpm BPM速度 * @param beatCount 拍数(默认2) * @returns 节拍器时间(秒) */ export function getFixTime(bpm: number, beatCount: number = DEFAULT_METRONOME_BEATS): number { if (bpm <= 0) { console.warn('[TimeCalculator] BPM必须大于0'); return 0; } return (60 / bpm) * beatCount; } /** * 将时值转换为秒 * @param realValue 时值(以四分音符为单位) * @param bpm BPM速度 * @param beatUnit 节拍单位(默认'1/4') * @returns 秒数 */ export function realValueToSeconds( realValue: number, bpm: number, beatUnit: string = '1/4' ): number { const beatUnitRatio = BEAT_UNIT_RATIO[beatUnit] ?? 1.0; const quarterNoteDuration = 60 / bpm; return realValue * beatUnitRatio * quarterNoteDuration; } /** * 将秒转换为时值 * @param seconds 秒数 * @param bpm BPM速度 * @param beatUnit 节拍单位(默认'1/4') * @returns 时值(以四分音符为单位) */ export function secondsToRealValue( seconds: number, bpm: number, beatUnit: string = '1/4' ): number { const beatUnitRatio = BEAT_UNIT_RATIO[beatUnit] ?? 1.0; const quarterNoteDuration = 60 / bpm; return seconds / (beatUnitRatio * quarterNoteDuration); } /** * 格式化时间为 MM:SS.mmm 格式 * @param seconds 秒数 * @returns 格式化后的时间字符串 */ export function formatTime(seconds: number): string { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); const ms = Math.round((seconds % 1) * 1000); return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`; } /** * 节拍单位转换 * @param fromUnit 源单位 * @param toBpm 目标BPM * @param toUnit 目标单位 * @returns 转换后的BPM */ export function convertBeatUnit(fromBpm: number, fromUnit: string, toUnit: string): number { const fromRatio = BEAT_UNIT_RATIO[fromUnit] ?? 1.0; const toRatio = BEAT_UNIT_RATIO[toUnit] ?? 1.0; return fromBpm * (fromRatio / toRatio); } /** * 保留小数精度 * @param value 数值 * @param precision 精度(小数位数,默认6) * @returns 保留精度后的数值 */ export function retain(value: number, precision: number = 6): number { const factor = Math.pow(10, precision); return Math.round(value * factor) / factor; } |