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 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | /** * OSMD数据解析器 * * @description 从OpenSheetMusicDisplay对象中解析简谱所需的数据 * * 核心功能: * 1. 解析曲谱元数据(标题、作曲家等) * 2. 解析小节信息(拍号、调号等) * 3. 解析音符数据(音高、时值、八度等) * 4. 保持OSMD原始数据引用(用于兼容层) */ import { JianpuScore } from '../../models/JianpuScore'; import { JianpuMeasure, BarlineType, createDefaultMeasure } from '../../models/JianpuMeasure'; import { JianpuNote, createDefaultNote } from '../../models/JianpuNote'; import { DivisionsHandler } from './DivisionsHandler'; import { DEFAULT_RENDER_CONFIG } from '../config/RenderConfig'; import { BarlineParser, MeasureBarlineInfo } from './BarlineParser'; // ==================== 常量定义 ==================== /** 音名到简谱数字的映射 */ const STEP_TO_JIANPU: Record<string, number> = { 'C': 1, 'D': 2, 'E': 3, 'F': 4, 'G': 5, 'A': 6, 'B': 7 }; /** 基准八度(中央C所在的八度) */ const BASE_OCTAVE = 4; /** 音符类型到时值的映射 */ const TYPE_TO_DURATION: Record<string, number> = { '1024th': 1/256, '512th': 1/128, '256th': 1/64, '128th': 1/32, '64th': 1/16, '32nd': 1/8, '16th': 0.25, 'eighth': 0.5, 'quarter': 1.0, 'half': 2.0, 'whole': 4.0, 'breve': 8.0, 'long': 16.0, 'maxima': 32.0, }; /** 升降号数量到调名的映射 */ const FIFTHS_TO_KEY: Record<number, { key: string; mode: string }> = { '-7': { key: 'Cb', mode: 'major' }, '-6': { key: 'Gb', mode: 'major' }, '-5': { key: 'Db', mode: 'major' }, '-4': { key: 'Ab', mode: 'major' }, '-3': { key: 'Eb', mode: 'major' }, '-2': { key: 'Bb', mode: 'major' }, '-1': { key: 'F', mode: 'major' }, '0': { key: 'C', mode: 'major' }, '1': { key: 'G', mode: 'major' }, '2': { key: 'D', mode: 'major' }, '3': { key: 'A', mode: 'major' }, '4': { key: 'E', mode: 'major' }, '5': { key: 'B', mode: 'major' }, '6': { key: 'F#', mode: 'major' }, '7': { key: 'C#', mode: 'major' }, }; // ==================== 类型定义 ==================== /** OSMD实例类型(简化定义,避免依赖OSMD类型) */ interface OSMDInstance { GraphicSheet?: { MeasureList?: any[][]; }; Sheet?: { Title?: { text?: string }; Subtitle?: { text?: string }; Composer?: { text?: string }; Lyricist?: { text?: string }; Instruments?: any[]; SourceMeasures?: any[]; }; cursor?: { Iterator?: any; reset?: () => void; next?: () => void; }; } /** 解析选项 */ export interface ParseOptions { /** 是否跳过装饰音 */ skipGraceNotes?: boolean; /** 是否包含多声部 */ includeMultiVoice?: boolean; /** 默认速度(BPM) */ defaultTempo?: number; /** 是否启用调试日志 */ debug?: boolean; } /** 解析结果统计 */ export interface ParseStats { measureCount: number; noteCount: number; voiceCount: number; restCount: number; graceNoteCount: number; parseTime: number; } // ==================== 主类 ==================== /** * OSMD数据解析器 */ export class OSMDDataParser { /** Divisions处理器 */ private divisionsHandler: DivisionsHandler; /** 解析选项 */ private options: Required<Omit<ParseOptions, 'debug'>> & { debug: boolean }; /** 解析统计 */ private stats: ParseStats = { measureCount: 0, noteCount: 0, voiceCount: 0, restCount: 0, graceNoteCount: 0, parseTime: 0, }; /** 音符ID计数器 */ private noteIdCounter: number = 0; /** 日志输出(受debug开关控制) */ private log(...args: any[]): void { if (this.options.debug) { console.log('[OSMDDataParser]', ...args); } } /** * 构造函数 * @param options 解析选项 */ constructor(options: ParseOptions = {}) { this.divisionsHandler = new DivisionsHandler(); this.options = { skipGraceNotes: options.skipGraceNotes ?? false, includeMultiVoice: options.includeMultiVoice ?? true, defaultTempo: options.defaultTempo ?? 120, debug: options.debug ?? false, }; } /** * 从OSMD对象解析简谱数据 * * @param osmd OpenSheetMusicDisplay实例 * @returns 简谱数据结构 */ parse(osmd: OSMDInstance): JianpuScore { const startTime = performance.now(); this.log('开始解析OSMD数据'); // 验证OSMD对象 if (!osmd) { throw new Error('[OSMDDataParser] OSMD实例不能为空'); } // 重置状态 this.resetState(); // 1. 提取元数据 const metadata = this.extractMetadata(osmd); this.log(`元数据: 标题="${metadata.title}", 作曲="${metadata.composer}"`); // 2. 解析小节 const measures = this.parseMeasures(osmd); this.log(`解析了 ${measures.length} 个小节`); // 3. 解析音符(填充到小节中) this.parseNotes(osmd, measures); this.log(`解析了 ${this.stats.noteCount} 个音符`); // 4. 构建JianpuScore const score: JianpuScore = { title: metadata.title, subtitle: metadata.subtitle, composer: metadata.composer, lyricist: metadata.lyricist, systems: [], // 布局引擎会填充 measures, tempo: metadata.tempo, initialTimeSignature: measures[0]?.timeSignature ?? { beats: 4, beatType: 4 }, initialKeySignature: measures[0]?.keySignature ?? { key: 'C', mode: 'major' }, config: { ...DEFAULT_RENDER_CONFIG }, totalMeasures: measures.length, voiceCount: this.stats.voiceCount, metadata: { parseStats: { ...this.stats }, }, }; // 计算总时长 score.duration = this.calculateTotalDuration(measures, metadata.tempo); this.stats.parseTime = performance.now() - startTime; this.log(`解析完成,耗时 ${this.stats.parseTime.toFixed(2)}ms`); return score; } /** * 获取解析统计 */ getStats(): ParseStats { return { ...this.stats }; } // ==================== 私有方法 ==================== /** * 重置解析状态 */ private resetState(): void { this.divisionsHandler.reset(); this.noteIdCounter = 0; this.stats = { measureCount: 0, noteCount: 0, voiceCount: 0, restCount: 0, graceNoteCount: 0, parseTime: 0, }; } /** * 生成唯一音符ID */ private generateNoteId(): string { return `note-${++this.noteIdCounter}`; } /** * 提取曲谱元数据 */ private extractMetadata(osmd: OSMDInstance): { title: string; subtitle?: string; composer?: string; lyricist?: string; tempo: number; } { const sheet = osmd.Sheet; let tempo = this.options.defaultTempo; // 尝试从第一个小节获取速度 if (sheet?.SourceMeasures?.[0]) { const firstMeasure = sheet.SourceMeasures[0]; if (firstMeasure.tempoInBPM) { tempo = firstMeasure.tempoInBPM; } else if (firstMeasure.TempoExpressions?.[0]?.InstantaneousTempo?.tempoInBpm) { tempo = firstMeasure.TempoExpressions[0].InstantaneousTempo.tempoInBpm; } } return { title: sheet?.Title?.text ?? 'Untitled', subtitle: sheet?.Subtitle?.text, composer: sheet?.Composer?.text, lyricist: sheet?.Lyricist?.text, tempo, }; } /** * 解析小节信息 */ private parseMeasures(osmd: OSMDInstance): JianpuMeasure[] { const measures: JianpuMeasure[] = []; // 优先使用SourceMeasures(更准确) const sourceMeasures = osmd.Sheet?.SourceMeasures; if (sourceMeasures && sourceMeasures.length > 0) { for (let i = 0; i < sourceMeasures.length; i++) { const srcMeasure = sourceMeasures[i]; const measure = this.parseSourceMeasure(srcMeasure, i); measures.push(measure); } } else { // 回退到GraphicSheet.MeasureList const measureList = osmd.GraphicSheet?.MeasureList; if (measureList && measureList.length > 0) { for (let i = 0; i < measureList.length; i++) { const graphicalMeasures = measureList[i]; if (graphicalMeasures && graphicalMeasures.length > 0) { const measure = this.parseGraphicalMeasure(graphicalMeasures[0], i); measures.push(measure); } } } } this.stats.measureCount = measures.length; return measures; } /** * 解析SourceMeasure */ private parseSourceMeasure(srcMeasure: any, index: number): JianpuMeasure { // 获取拍号 const timeSig = srcMeasure.ActiveTimeSignature; const timeSignature = { beats: timeSig?.numerator ?? timeSig?.Numerator ?? 4, beatType: timeSig?.denominator ?? timeSig?.Denominator ?? 4, }; // 获取调号 const keySig = srcMeasure.ActiveKeySignature; const keySignature = this.parseKeySignature(keySig); // 获取速度 let tempo: number | undefined; if (srcMeasure.tempoInBPM) { tempo = srcMeasure.tempoInBPM; } else if (srcMeasure.TempoExpressions?.[0]?.InstantaneousTempo?.tempoInBpm) { tempo = srcMeasure.TempoExpressions[0].InstantaneousTempo.tempoInBpm; } // 创建小节 const measure = createDefaultMeasure(index + 1, timeSignature); measure.keySignature = keySignature; if (tempo !== undefined) { measure.tempo = tempo; } // 小节线类型 measure.barlineType = this.getBarlineType(srcMeasure); // 是否显示拍号/调号(第一小节或变化时显示) measure.showTimeSignature = index === 0; measure.showKeySignature = index === 0; return measure; } /** * 解析GraphicalMeasure */ private parseGraphicalMeasure(graphicalMeasure: any, index: number): JianpuMeasure { const srcMeasure = graphicalMeasure.parentSourceMeasure; if (srcMeasure) { return this.parseSourceMeasure(srcMeasure, index); } // 如果没有SourceMeasure,创建默认小节 return createDefaultMeasure(index + 1); } /** * 解析调号 */ private parseKeySignature(keySig: any): { key: string; mode: 'major' | 'minor'; alterations?: number; } { if (!keySig) { return { key: 'C', mode: 'major', alterations: 0 }; } const fifths = keySig.keyTypeOriginal ?? keySig.Key ?? 0; const mode = keySig.Mode ?? 0; // 0 = major, 1 = minor const keyInfo = FIFTHS_TO_KEY[fifths.toString()] ?? { key: 'C', mode: 'major' }; return { key: keyInfo.key, mode: mode === 1 ? 'minor' : 'major', alterations: fifths, }; } /** * 获取小节线类型 * * 支持多种数据来源: * 1. OSMD 的 lastRepetitionInstructions * 2. 直接从 MusicXML 解析的 barStyle/hasRepeatBackward/hasRepeatForward * 3. endingBarStyleEnum/endingBarStyle 属性 * 4. 使用BarlineParser解析的barlineInfo * * @see https://www.w3.org/2021/06/musicxml40/musicxml-reference/elements/barline/ */ private getBarlineType(srcMeasure: any): BarlineType { // 如果有预解析的barline信息(来自BarlineParser) const barlineInfo = srcMeasure.barlineInfo as MeasureBarlineInfo | undefined; if (barlineInfo) { return barlineInfo.barlineType; } // 获取小节线样式 const barStyle = srcMeasure.barStyle ?? srcMeasure.endingBarStyleEnum ?? srcMeasure.endingBarStyle; // 方式1:从 OSMD 的 repetition instructions 获取 const instructions = srcMeasure.lastRepetitionInstructions; if (instructions && instructions.length > 0) { for (const inst of instructions) { const type = inst.type; if (type === 'StartLine' || type === 2) return 'repeat-start'; if (type === 'BackJumpLine' || type === 3) { // 如果是终止线样式的反复结束 return barStyle === 'light-heavy' ? 'repeat-end-final' : 'repeat-end'; } if (type === 'Ending') return 'double'; } } // 方式2:从直接解析的 MusicXML 属性获取(如 visual-test.html 中的解析结果) // 检查反复记号 if (srcMeasure.hasRepeatBackward) { // 如果同时是终止线样式(light-heavy),使用 repeat-end-final return barStyle === 'light-heavy' ? 'repeat-end-final' : 'repeat-end'; } if (srcMeasure.hasRepeatForward) { return 'repeat-start'; } // 方式3:根据bar-style映射 // 完整支持MusicXML 4.0规范中的bar-style值 return this.mapBarStyleToType(barStyle); } /** * 将MusicXML bar-style映射到BarlineType * * @param barStyle MusicXML bar-style值 * @returns 对应的BarlineType * @see https://www.w3.org/2021/06/musicxml40/musicxml-reference/elements/barline/ */ private mapBarStyleToType(barStyle: string | undefined): BarlineType { if (!barStyle) return 'single'; switch (barStyle) { // 普通单线 case 'regular': case 'light': return 'single'; // 双细线 case 'light-light': case 'double': return 'double'; // 终止线(左细右粗) case 'light-heavy': return 'final'; // 开始线(左粗右细)- 通常用于反复开始 case 'heavy-light': return 'repeat-start'; // 单粗线 case 'heavy': return 'heavy'; // 双粗线 case 'heavy-heavy': return 'heavy-heavy'; // 点线 case 'dotted': return 'dotted'; // 虚线 case 'dashed': return 'dashed'; // 短刻度(仅顶部) case 'tick': return 'tick'; // 短线 case 'short': return 'short'; // 无小节线 case 'none': return 'none'; default: return 'single'; } } /** * 解析音符信息 */ private parseNotes(osmd: OSMDInstance, measures: JianpuMeasure[]): void { const cursor = osmd.cursor; if (!cursor?.Iterator) { console.warn('[OSMDDataParser] 无法获取cursor.Iterator,尝试从MeasureList解析'); this.parseNotesFromMeasureList(osmd, measures); return; } // 使用cursor遍历 cursor.reset?.(); const iterator = cursor.Iterator; let maxVoiceIndex = 0; while (!iterator.EndReached) { const voiceEntries = iterator.currentVoiceEntries ?? iterator.CurrentVoiceEntries ?? []; const measureIndex = iterator.currentMeasureIndex ?? 0; if (measureIndex >= 0 && measureIndex < measures.length) { const measure = measures[measureIndex]; const timestamp = iterator.currentTimeStamp?.RealValue ?? iterator.currentTimeStamp?.realValue ?? 0; for (const voiceEntry of voiceEntries) { const voiceIndex = voiceEntry.ParentVoice?.VoiceId ?? 0; maxVoiceIndex = Math.max(maxVoiceIndex, voiceIndex); // 确保声部数组存在 while (measure.voices.length <= voiceIndex) { measure.voices.push([]); } const notes = voiceEntry.Notes ?? voiceEntry.notes ?? []; for (const note of notes) { const jianpuNote = this.parseNote(note, measureIndex, voiceIndex, timestamp); if (jianpuNote) { measure.voices[voiceIndex].push(jianpuNote); this.stats.noteCount++; if (jianpuNote.isRest) this.stats.restCount++; if (jianpuNote.isGraceNote) this.stats.graceNoteCount++; } } } } // 移动到下一个 try { if (iterator.moveToNextVisibleVoiceEntry) { iterator.moveToNextVisibleVoiceEntry(this.options.skipGraceNotes); } else { cursor.next?.(); } } catch (e) { console.warn('[OSMDDataParser] Iterator移动失败:', e); break; } } this.stats.voiceCount = maxVoiceIndex + 1; // 同步notes和voices引用 for (const measure of measures) { measure.notes = measure.voices; } } /** * 从MeasureList解析音符(备用方案) */ private parseNotesFromMeasureList(osmd: OSMDInstance, measures: JianpuMeasure[]): void { const measureList = osmd.GraphicSheet?.MeasureList; if (!measureList) { console.warn('[OSMDDataParser] 无法获取MeasureList'); return; } let maxVoiceIndex = 0; for (let measureIdx = 0; measureIdx < measureList.length && measureIdx < measures.length; measureIdx++) { const graphicalMeasures = measureList[measureIdx]; const measure = measures[measureIdx]; if (!graphicalMeasures) continue; for (const gMeasure of graphicalMeasures) { if (!gMeasure?.staffEntries) continue; for (const staffEntry of gMeasure.staffEntries) { const timestamp = staffEntry.relInMeasureTimestamp?.RealValue ?? 0; const voiceEntries = staffEntry.graphicalVoiceEntries ?? []; for (const gve of voiceEntries) { const voiceIndex = gve.parentVoiceEntry?.ParentVoice?.VoiceId ?? 0; maxVoiceIndex = Math.max(maxVoiceIndex, voiceIndex); // 确保声部数组存在 while (measure.voices.length <= voiceIndex) { measure.voices.push([]); } const notes = gve.notes ?? []; for (const graphicalNote of notes) { const srcNote = graphicalNote.sourceNote; if (!srcNote) continue; const jianpuNote = this.parseNote(srcNote, measureIdx, voiceIndex, timestamp); if (jianpuNote) { // 保存图形化音符的SVG引用 if (graphicalNote.vfnote?.[0]?.attrs?.id) { jianpuNote.osmdCompatible.svgElement.attrs.id = graphicalNote.vfnote[0].attrs.id; } // 解析歌词(从 parentVoiceEntry 获取) const parentVoiceEntry = gve.parentVoiceEntry; if (parentVoiceEntry?.LyricsEntries) { jianpuNote.lyrics = this.parseLyricsFromVoiceEntry(parentVoiceEntry); } measure.voices[voiceIndex].push(jianpuNote); this.stats.noteCount++; if (jianpuNote.isRest) this.stats.restCount++; if (jianpuNote.isGraceNote) this.stats.graceNoteCount++; } } } } } } this.stats.voiceCount = maxVoiceIndex + 1; // 同步notes和voices引用 for (const measure of measures) { measure.notes = measure.voices; } } /** * 解析单个音符 */ private parseNote( note: any, measureIndex: number, voiceIndex: number, timestamp: number ): JianpuNote | null { // 跳过装饰音(如果配置了) if (this.options.skipGraceNotes && note.IsGraceNote) { return null; } const isRest = note.isRestFlag ?? note.IsRest ?? note.isRest ?? false; const isGraceNote = note.IsGraceNote ?? note.isGraceNote ?? false; // 获取音高信息 let pitch = 0; let octave = 0; let accidental: JianpuNote['accidental'] = undefined; let halfTone = 0; let frequency = 0; if (!isRest && note.pitch) { pitch = this.getPitchNumber(note); octave = this.getOctaveOffset(note); accidental = this.getAccidental(note); halfTone = note.halfTone ?? this.calculateHalfTone(note); frequency = note.pitch?.frequency ?? this.halfToneToFrequency(halfTone); } // 获取时值 const duration = this.getNoteDuration(note); const dots = this.getDotCount(note); // 创建音符 const jianpuNote = createDefaultNote({ pitch, octave, duration, accidental, dots, timestamp, voiceIndex, measureIndex, isRest, isGraceNote, isStaccato: note.isStaccato ?? false, }); // 设置ID jianpuNote.id = this.generateNoteId(); // 解析歌词(从多个来源尝试获取) jianpuNote.lyrics = this.parseLyricsFromNote(note); // 设置OSMD兼容数据 jianpuNote.osmdCompatible = { noteElement: note, svgElement: { attrs: { id: `vf-${jianpuNote.id}` }, modifiers: note.modifiers, }, halfTone, frequency, realKey: pitch > 0 ? pitch + octave * 7 : 0, }; return jianpuNote; } /** * 从音符对象解析歌词 * 支持多种数据格式(OSMD/直接解析XML的格式) */ private parseLyricsFromNote(note: any): { text: string; index: number }[] { const lyrics: { text: string; index: number }[] = []; try { // 格式1:直接的 lyrics 数组(如 visual-test.html 中的解析格式) if (Array.isArray(note.lyrics)) { for (const lyric of note.lyrics) { if (lyric.text) { // number 是 1-based,转为 0-based index const index = (lyric.number ?? lyric.index ?? 1) - 1; lyrics.push({ text: lyric.text, index: Math.max(0, index), }); } } return lyrics; } // 格式2:OSMD 的 LyricsEntries(在 voiceEntry 上) // 这部分在 parseNotesFromMeasureList 中处理 } catch (e) { console.warn('[OSMDDataParser] 解析歌词失败:', e); } return lyrics; } /** * 获取简谱音高(1-7) */ private getPitchNumber(note: any): number { // 方式1:从pitch.step获取 const step = note.pitch?.step ?? note.pitch?.Step; if (step !== undefined) { const pitch = STEP_TO_JIANPU[step.toString().toUpperCase()]; if (pitch !== undefined) { return pitch; } } // 方式2:从halfTone计算 const halfTone = note.halfTone ?? note.HalfTone; if (halfTone !== undefined) { // halfTone % 12 得到音级,映射到1-7 const noteInOctave = ((halfTone % 12) + 12) % 12; const halfToneToJianpu = [1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 7]; // C C# D D# E F F# G G# A A# B return halfToneToJianpu[noteInOctave]; } console.warn('[OSMDDataParser] 无法获取音高信息,返回默认值1'); return 1; } /** * 获取八度偏移 */ private getOctaveOffset(note: any): number { // 方式1:从pitch.octave获取 const octave = note.pitch?.octave ?? note.pitch?.Octave; if (octave !== undefined) { return octave - BASE_OCTAVE; } // 方式2:从halfTone计算 const halfTone = note.halfTone ?? note.HalfTone; if (halfTone !== undefined) { const octaveFromHalfTone = Math.floor(halfTone / 12) - 1; // MIDI标准 return octaveFromHalfTone - BASE_OCTAVE; } return 0; } /** * 获取升降号 * * 注意:只有当音符有显式的升降号标记时才返回对应类型 * - alter = 0 且没有 accidental 标记时,表示自然音,不需要显示任何记号 * - alter = 0 且有 accidental="natural" 时,才需要显示还原号 */ private getAccidental(note: any): JianpuNote['accidental'] | undefined { // 优先从 accidental 属性获取(MusicXML 中的显式升降号标记) const accidental = note.accidental ?? note.Accidental; if (accidental) { const accStr = accidental.toString().toLowerCase(); if (accStr.includes('sharp')) return 'sharp'; if (accStr.includes('flat')) return 'flat'; if (accStr.includes('natural')) return 'natural'; } // 从 pitch.alter 获取(只处理非零值) const alter = note.pitch?.alter ?? note.pitch?.Alter; // 只有 alter 明确为 +1/+2 或 -1/-2 时才返回升/降号 // alter === 0 或 undefined 表示自然音,不显示任何记号 if (alter === 1 || alter === 2) return 'sharp'; if (alter === -1 || alter === -2) return 'flat'; // 注意:alter === 0 不返回 'natural',因为这只表示"没有变化" // 还原号只在显式标记 accidental="natural" 时显示 return undefined; } /** * 获取音符时值 */ private getNoteDuration(note: any): number { // 方式1:从length.realValue获取(最准确) const realValue = note.length?.RealValue ?? note.length?.realValue; if (realValue !== undefined && realValue > 0) { return realValue; } // 方式2:从noteType获取 const noteType = note.noteTypeXml ?? note.TypeLength?.toString() ?? note.type; if (noteType) { const baseDuration = TYPE_TO_DURATION[noteType.toLowerCase()]; if (baseDuration !== undefined) { // 应用附点 const dots = this.getDotCount(note); return this.divisionsHandler.applyDots(baseDuration, dots); } } // 方式3:从duration和divisions计算 const duration = note.duration ?? note.Duration; if (duration !== undefined) { const sourceMeasure = note.sourceMeasure ?? note.SourceMeasure; const divisions = sourceMeasure?.divisions ?? 256; this.divisionsHandler.setDivisions(divisions); return this.divisionsHandler.toRealValue(duration); } console.warn('[OSMDDataParser] 无法获取音符时值,返回默认值1.0'); return 1.0; } /** * 获取附点数量 */ private getDotCount(note: any): number { // 方式1:直接获取dots数量 const dots = note.dots ?? note.Dots ?? note.DotsXml; if (typeof dots === 'number') { return dots; } // 方式2:从数组长度获取 if (Array.isArray(dots)) { return dots.length; } return 0; } /** * 从VoiceEntry解析歌词 */ private parseLyricsFromVoiceEntry(voiceEntry: any): { text: string; index: number }[] { const lyrics: { text: string; index: number }[] = []; try { const lyricsEntries = voiceEntry.LyricsEntries; if (!lyricsEntries) return lyrics; // LyricsEntries 是一个 Dictionary<string, LyricsEntry> // 尝试遍历它 if (typeof lyricsEntries.forEach === 'function') { lyricsEntries.forEach((key: string, entry: any) => { if (entry && entry.Text) { const verseNumber = parseInt(entry.VerseNumber ?? '1', 10) || 1; lyrics.push({ text: entry.Text, index: verseNumber - 1 // 转为0索引 }); } }); } else if (typeof lyricsEntries.keys === 'function') { // 另一种可能的结构 const keys = lyricsEntries.keys(); for (const key of keys) { const entry = lyricsEntries.getValue(key); if (entry && entry.Text) { const verseNumber = parseInt(entry.VerseNumber ?? '1', 10) || 1; lyrics.push({ text: entry.Text, index: verseNumber - 1 }); } } } } catch (e) { console.warn('[OSMDDataParser] 解析歌词失败:', e); } return lyrics; } /** * 计算半音值(从音高信息) */ private calculateHalfTone(note: any): number { const step = note.pitch?.step ?? note.pitch?.Step; const octave = note.pitch?.octave ?? note.pitch?.Octave ?? 4; const alter = note.pitch?.alter ?? note.pitch?.Alter ?? 0; if (!step) return 60; // 默认C4 const stepToSemitone: Record<string, number> = { 'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11 }; const semitone = stepToSemitone[step.toString().toUpperCase()] ?? 0; return (octave + 1) * 12 + semitone + alter; } /** * 半音值转频率 */ private halfToneToFrequency(halfTone: number): number { // A4 = 440Hz, MIDI note 69 return 440 * Math.pow(2, (halfTone - 69) / 12); } /** * 计算总时长 */ private calculateTotalDuration(measures: JianpuMeasure[], tempo: number): number { let totalBeats = 0; for (const measure of measures) { const { beats, beatType } = measure.timeSignature; // 将节拍数转换为四分音符数量 const quarterNotesInMeasure = beats * (4 / beatType); totalBeats += quarterNotesInMeasure; } // 四分音符时长 = 60 / BPM const quarterNoteDuration = 60 / tempo; return totalBeats * quarterNoteDuration; } } // ==================== 工厂函数 ==================== /** * 创建OSMD数据解析器 */ export function createOSMDDataParser(options?: ParseOptions): OSMDDataParser { return new OSMDDataParser(options); } // ==================== 工具函数(导出供其他模块使用) ==================== /** * 音名转简谱数字 */ export function stepToJianpu(step: string): number { const pitch = STEP_TO_JIANPU[step.toUpperCase()]; if (pitch === undefined) { throw new Error(`无效的音名: ${step}`); } return pitch; } /** * 八度转偏移 */ export function octaveToOffset(octave: number): number { return octave - BASE_OCTAVE; } /** * 升降号值转类型 */ export function alterToAccidental(alter: number | null): 'sharp' | 'flat' | 'natural' | null { if (alter === null || alter === undefined) return null; if (alter > 0) return 'sharp'; if (alter < 0) return 'flat'; return 'natural'; } /** * 音符类型转时值 */ export function noteTypeToRealValue(noteType: string): number { const duration = TYPE_TO_DURATION[noteType.toLowerCase()]; if (duration === undefined) { console.warn(`未知的音符类型: ${noteType}`); return 1.0; } return duration; } |