123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836 |
- import dayjs from "dayjs";
- import duration from "dayjs/plugin/duration";
- import state, { customData } from "/src/state";
- import { browser } from "../utils/index";
- import { transferJianNote } from "/src/helpers/customMusicScore"
- import {
- isSpecialMark,
- isSpeedKeyword,
- Fraction,
- SourceMeasure,
- isGradientWords,
- GRADIENT_SPEED_RESET_TAG,
- StringUtil,
- OpenSheetMusicDisplay,
- } from "/osmd-extended/src";
- import { GradualChange, speedInfo } from "./calcSpeed";
- import { beatUnitTo, speedBeatTo } from "/src/helpers/beatConfig"
- import { xmlDocRef } from "/src/view/music-score"
- const browserInfo = browser();
- dayjs.extend(duration);
- const hideSpeedWords: string[] = ["中速"];
- export const getFixTime = (speed: number) => {
- const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
- let numerator = duration.numerator || 0;
- let denominator = duration.denominator || 4;
- const beatUnit = "quarter";
-
-
-
-
-
-
-
- if (state.repeatedBeats) {
- numerator = numerator*2;
- }
-
- return (60 / speed) * formatBeatUnit(beatUnit) * (numerator / denominator);
- };
- export const retain = (time: number) => {
- return Math.ceil(time * 1000000) / 1000000;
- };
- export const formatLyricsEntries = (note: any) => {
- const voiceEntries = note.parentStaffEntry?.voiceEntries || [];
- const lyricsEntries: string[] = [];
- for (const voic of voiceEntries) {
- if (voic.lyricsEntries?.table) {
- const values: any[] = Object.values(voic.lyricsEntries.table);
- for (const lyric of values) {
- lyricsEntries.push(lyric?.value.text);
- }
- }
- }
- return lyricsEntries;
- };
- export const getMeasureDurationDiff = (measure: any) => {
- const { realValue: SRealValue } = measure.activeTimeSignature;
- const { realValue: RRealValue } = measure.duration;
- return SRealValue - RRealValue;
- };
- export const createSpeedInfo = (gradualChange: GradualChange | undefined, speed: number) => {
- if (gradualChange && speedInfo[gradualChange.startWord?.toLocaleLowerCase()]) {
- const notenum = Math.max(gradualChange.endXmlNoteIndex, 3);
- const speeds: number[] = [];
- const startSpeed = speed;
- const endSpeed = speed / speedInfo[gradualChange.startWord?.toLocaleLowerCase()];
- for (let index = 0; index < notenum; index++) {
- const speed = startSpeed + ((endSpeed - startSpeed) / notenum) * (index + 1);
- speeds.push(speed);
- }
- return speeds;
- }
- return;
- };
- const tranTime = (str: string = "") => {
- let result = str;
- const splits = str.split(":");
- if (splits.length === 1) {
- result = `00:${splits[0]}:00`;
- } else if (splits.length === 2) {
- result = `00:${splits[0]}:${splits[1]}`;
- }
-
- return `1970-01-01 00:${result}0`;
- };
- export const getSlursNote = (note: any, pos?: "start" | "end") => {
- return pos === "end" ? note.noteElement.slurs[0]?.endNote : note.noteElement.slurs[0]?.startNote;
- };
- export const getNoteBySlursStart = (note: any, anyNoteHasSlurs?: boolean, pos?: "start" | "end") => {
- let activeNote = note;
- let slursNote = getSlursNote(activeNote, pos);
- for (const item of activeNote.measures) {
- if (item.noteElement.slurs.length) {
- slursNote = getSlursNote(item, pos);
- activeNote = item;
- }
- }
- return activeNote;
- };
- export const getParentNote = (note: any) => {
- let parentNote;
- if (note) {
-
- for (const n of state.times) {
- if (note === n.noteElement) {
-
- return n;
- }
- }
- }
- return parentNote;
- };
- export type FractionDefault = {
- numerator: number;
- denominator: number;
- wholeValue: number;
- };
- export type Duration = FractionDefault & {
- TempoInBPM: number;
- beatUnit: string;
- };
- export const getDuration = (osmd?: OpenSheetMusicDisplay): Duration => {
- if (osmd) {
- const { Duration, TempoInBPM, ActiveTimeSignature, TempoExpressions } = osmd.GraphicSheet.MeasureList[0][0]?.parentSourceMeasure;
- if (Duration) {
- let beatUnit = "quarter";
-
-
-
- const duration = formatDuration(ActiveTimeSignature, Duration) as unknown as FractionDefault;
- return {
- ...duration,
- TempoInBPM,
- beatUnit,
- };
- }
- }
- const duration = new Fraction() as unknown as FractionDefault;
- return {
- ...duration,
- TempoInBPM: 90,
- beatUnit: "quarter",
- };
- };
- export function formatDuration(activeTimeSignature: Fraction, duration: Fraction): Fraction {
-
- return activeTimeSignature;
- }
- export function formatBeatUnit(beatUnit: string) {
- let multiple = 4;
- switch (beatUnit) {
- case "1024th":
-
- multiple = 1024;
- break;
- case "512th":
-
- multiple = 512;
- break;
- case "256th":
-
- multiple = 256;
- break;
- case "128th":
-
- multiple = 128;
- break;
- case "64th":
-
- multiple = 64;
- break;
- case "32nd":
-
- multiple = 32;
- break;
- case "16th":
-
- multiple = 16;
- break;
- case "eighth":
-
- multiple = 8;
- break;
- case "quarter":
- multiple = 4;
- break;
- case "half":
-
- multiple = 2;
- break;
- case "whole":
-
- multiple = 1;
- break;
- case "breve":
-
- multiple = 0.5;
- break;
- case "long":
-
- multiple = 0.25;
- break;
- case "maxima":
-
- multiple = 0.125;
- break;
- default:
- break;
- }
- return multiple;
- }
- export type CustomInfo = {
- showSpeed: boolean;
- parsedXML: string;
- };
- export const getCustomInfo = (xml: string, resourceType?: string): CustomInfo => {
- const data = {
- showSpeed: true,
- parsedXML: xml,
- };
-
-
- const xmlParse = xmlDocRef.value && resourceType === 'init' ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
-
- const words: any = xmlParse?.getElementsByTagName("words");
- for (const word of words) {
- if (word && word.textContent?.trim() === "隐藏速度") {
- data.showSpeed = false;
- word.textContent = "";
- }
- if (word && word.textContent?.trim() === "@") {
- word.textContent = "segno";
- }
- }
- data.parsedXML = new XMLSerializer().serializeToString(xmlParse);
- return data;
- };
- const replaceTextConent = (beforeText: string, afterText: string, ele: Element): Element => {
- const words: any = ele?.getElementsByTagName("words");
- for (const word of words) {
- if (word && word.textContent?.trim() === beforeText) {
- word.textContent = afterText;
- }
- }
- return ele;
- };
- const setElementNoteBefore = (ele: Element, fitstParent: Element, parent?: Element | null) => {
- let noteIndex: number = 0;
- if (!fitstParent) {
- return;
- }
- for (let index = 0; index < fitstParent.childNodes.length; index++) {
- const element = fitstParent.childNodes[index];
- if (element.nodeName === "note") {
- noteIndex++;
- }
- if (element === ele) {
- break;
- }
- }
- if (noteIndex === 0 && parent) {
- parent.insertBefore(ele, parent.childNodes[0]);
- return;
- }
- if (parent && parent.childNodes.length > 0) {
- let noteIndex2: number = 0;
- const notes = Array.from(parent.childNodes).filter((child) => child.nodeName === "note");
- const lastNote = notes[notes.length - 1];
- if (noteIndex >= notes.length && lastNote) {
- parent.insertBefore(ele, parent.childNodes[Array.from(parent.childNodes).indexOf(lastNote)]);
- return;
- }
- for (let index = 0; index < notes.length; index++) {
- const element = notes[index];
- if (element.nodeName === "note") {
- noteIndex2 = noteIndex2 + 1;
- if (noteIndex2 === noteIndex) {
- parent.insertBefore(ele, element);
- break;
- }
- }
- }
- }
-
- };
- export const isRepeatWord = (text: string): boolean => {
- if (text) {
- const innerText = text.toLocaleLowerCase();
- const dsRegEx: string = "d\\s?\\.s\\.";
- const dcRegEx: string = "d\\.\\s?c\\.";
- return (
- innerText === "@" ||
- StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al fine", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al fine", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, dcRegEx) ||
- StringUtil.StringContainsSeparatedWord(innerText, "da\\s?capo", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, dsRegEx, true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "dal\\s?segno", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "al\\s?coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "to\\s?coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "a (la )?coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "fine", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "coda", true) ||
- StringUtil.StringContainsSeparatedWord(innerText, "segno", true)
- );
- }
- return false;
- };
- export const onlyVisible = (xml: string, partIndex: number, resourceType?: string): string => {
- if (!xml) return "";
-
- const detailId = state.examSongId + "";
-
-
- const xmlParse = xmlDocRef.value && !resourceType ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
-
- const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
- const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");
- const parts: any = xmlParse.getElementsByTagName("part");
-
- const firstMeasures = [...parts[0]?.getElementsByTagName("measure")];
- const metronomes = [...parts[0]?.getElementsByTagName("metronome")];
- const words = [...parts[0]?.getElementsByTagName("words")];
- const codas = [...parts[0]?.getElementsByTagName("coda")];
- const rehearsals = [...parts[0]?.getElementsByTagName("rehearsal")];
-
- if (partListNames[0]?.toLocaleUpperCase?.() === "COMMON") {
- partIndex++;
- partListNames.shift();
- }
- const visiblePartInfo = partList[partIndex];
-
-
-
-
- if (visiblePartInfo) {
- const id = visiblePartInfo.getAttribute("id");
- Array.from(parts).forEach((part: any) => {
- if (part && part.getAttribute("id") !== id) {
- part.parentNode?.removeChild(part);
-
- } else if (part && part.getAttribute("id") !== "P1") {
-
- const metronomeData: {
- [key in string]: Element;
- } = {};
- for (let i = 0; i < metronomes.length; i++) {
- const metronome = metronomes[i];
- const metronomeContainer = metronome.parentElement?.parentElement?.parentElement;
- if (metronomeContainer) {
- const index = firstMeasures.indexOf(metronomeContainer);
- metronomeData[index] = metronome;
- }
- }
- Object.values(metronomeData).forEach((metronome) => {
- const metronomeContainer: any = metronome.parentElement?.parentElement;
- const parentMeasure: any = metronomeContainer?.parentElement;
- const measureMetronomes = [...(parentMeasure?.childNodes || [])];
- const metronomesIndex = metronomeContainer ? measureMetronomes.indexOf(metronomeContainer) : -1;
-
- if (parentMeasure && metronomesIndex > -1) {
- const index = firstMeasures.indexOf(parentMeasure);
- const activeMeasure = part.getElementsByTagName("measure")[index];
- setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
- }
- });
-
- words.forEach((word) => {
- let text = word.textContent || "";
- text = ["cresc."].includes(text) ? "" : text;
- if ((isSpecialMark(text) || isSpeedKeyword(text) || isGradientWords(text) || isRepeatWord(text) || GRADIENT_SPEED_RESET_TAG) && text) {
- const wordContainer = word.parentElement?.parentElement;
- const parentMeasure = wordContainer?.parentElement;
- const measureWords = [...(parentMeasure?.childNodes || [])];
- const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
- if (wordContainer && parentMeasure && wordIndex > -1) {
- const index = firstMeasures.indexOf(parentMeasure);
- const activeMeasure = part.getElementsByTagName("measure")[index];
-
- const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
-
- const total = _words.reduce((total: any, _word: any) => {
- if (_word.textContent?.includes(text)) {
- total++;
- }
- return total;
- }, 0);
- if (total === 0) {
- if (["12280"].includes(detailId)) {
- activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
- } else {
- setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
- }
- }
- }
- }
- });
-
- codas.forEach((coda) => {
- const wordContainer = coda.parentElement?.parentElement;
- const parentMeasure = wordContainer?.parentElement;
- const measureWords = [...(parentMeasure?.childNodes || [])];
- const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
- if (wordContainer && parentMeasure && wordIndex > -1) {
- const index = firstMeasures.indexOf(parentMeasure);
- const activeMeasure = part.getElementsByTagName("measure")[index];
- if (["12280"].includes(detailId)) {
- activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
- } else {
- setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
- }
- }
- });
- rehearsals.forEach((rehearsal) => {
- const container = rehearsal.parentElement?.parentElement;
- const parentMeasure = container?.parentElement;
-
- if (parentMeasure) {
- const index = firstMeasures.indexOf(parentMeasure);
- part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
-
- }
- });
- } else {
- words.forEach((word, idx) => {
- const text = word.textContent || "";
-
-
-
-
-
-
-
- if (isSpeedKeyword(text) && text) {
- const wordContainer = word.parentElement?.parentElement?.parentElement;
- if (wordContainer && wordContainer.firstElementChild && wordContainer.firstElementChild !== word) {
- const wordParent = word.parentElement?.parentElement;
- const fisrt = wordContainer.firstElementChild;
- wordContainer.insertBefore(wordParent, fisrt);
- }
- }
- });
- }
-
- if (part && part.getAttribute("id") === id) {
- if (!resourceType) {
- const backups = Array.from(part.getElementsByTagName('backup')) || []
- for (let backup of backups) {
-
- if (backup && backup?.getElementsByTagName('duration')?.length) {
- state.isSingleMutliTrack = true;
- break;
- }
- }
- }
- const barlines = part.getElementsByTagName("barline");
- const lastParent = barlines[barlines.length - 1]?.parentElement;
- if (lastParent?.lastElementChild?.tagName !== "barline") {
- const children = lastParent?.children || [];
- for (let el of children) {
- if (el.tagName === "barline") {
-
- lastParent?.appendChild(el);
- break;
- }
- }
- }
- }
- });
- Array.from(partList).forEach((part) => {
- if (part && part.getAttribute("id") !== id) {
- part.parentNode?.removeChild(part);
- }
- });
- }
-
- return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
- };
- export const onlyVisible2 = (xml: string): string => {
- if (!xml) return "";
-
-
- console.time('解析xml 耗时5')
- const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
- console.timeEnd('解析xml 耗时5')
- const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
-
-
- Array.from(partList).forEach((part) => {
- let partListName = part.getElementsByTagName("part-name")?.[0]?.textContent?.trim();
- if (!state.canSelectTracks.includes(partListName)) {
- part.parentNode?.removeChild(part);
- }
- });
-
- return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
- };
- export const appoggianceFormate = (xmlParse: Document): Document => {
- if (!xmlParse) return xmlParse;
- const graces: any = xmlParse.querySelectorAll("grace");
- if (!graces.length) return xmlParse;
- const getNextElement = (el: HTMLElement): HTMLElement => {
- if (el.querySelector("grace")) {
- return getNextElement(el?.nextElementSibling as HTMLElement);
- }
- return el;
- };
- for (let grace of graces) {
- const notations = grace.parentElement?.querySelector("notations");
- if (notations && notations.querySelectorAll("slur").length > 1) {
- let nextEle: Element = getNextElement(grace.parentElement?.nextElementSibling as HTMLElement);
- if (nextEle && nextEle.querySelectorAll("slur").length > 0) {
- const slurNumber = Array.from(nextEle.querySelector("notations")?.children || []).map((el: Element) => {
- return el.getAttribute("number");
- });
- const slurs = notations.querySelectorAll("slur");
- for (let nota of slurs) {
- if (!slurNumber.includes(nota.getAttribute("number"))) {
- nextEle.querySelector("notations")?.appendChild(nota);
- }
- }
- }
- }
- }
- return xmlParse;
- };
- export const isWithinScope = (tree: any[], id: number): number => {
- if (!tree) return 0;
- let result = 0;
- for (const item of tree) {
- if (item.id === id) {
- result = item.id;
- break;
- }
- if (item.sysMusicScoreCategoriesList) {
- result = isWithinScope(item.sysMusicScoreCategoriesList, id);
- if (result > 0) {
- result = item.id;
- }
- if (result) break;
- }
- }
- return result;
- };
- class NoteList {
- notes: any[] = [];
- constructor(notes: any[]) {
- this.notes = notes;
- }
- public last() {
- return this.notes[this.notes.length - 1];
- }
- public list() {
- return this.notes;
- }
- }
- export const getNotesByid = (id: string): NoteList => {
- const notes = new NoteList(state.times.filter((item) => item.id === id));
- return notes;
- };
- export const formatZoom = (num = 1) => {
- return num * state.zoom;
- };
- export const xmlAddPartName = (xml: string) => {
- if (!xml) return "";
- console.time('解析xml 耗时')
- const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
- console.timeEnd('解析xml 耗时')
- const scoreParts = Array.from(xmlParse.getElementsByTagName("score-part"));
- for (const scorePart of scoreParts) {
- if (scorePart.getElementsByTagName("part-name").length === 0) {
- state.evxmlAddPartName = true;
- const name = scorePart.getAttribute("id") || "";
- const newPartName = `<part-name>${name}</part-name>`
-
- scorePart.innerHTML = newPartName + scorePart.innerHTML;
- }
- if (scorePart.getElementsByTagName("part-name").length && !scorePart.getElementsByTagName("part-name")?.[0]?.textContent?.trim() ) {
- scorePart.getElementsByTagName("part-name")[0].textContent = scorePart.getAttribute("id") || "";
- }
- }
- xmlDocRef.value = xmlParse;
- return new XMLSerializer().serializeToString(xmlParse);
- }
- export const formatXML = (xml: string, xmlUrl?: string, resourceType?: string): string => {
- if (!xml) return "";
-
-
- const xmlParse = xmlDocRef.value && resourceType === 'init' ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
-
-
- const fifths = xmlParse.getElementsByTagName("fifths");
- if (fifths && fifths.length) {
-
- state.isCTone = fifths[0].textContent === '0'
- }
- const endings = Array.from(xmlParse.getElementsByTagName("ending"));
- for (const ending of endings) {
-
-
-
-
-
-
- }
- const measures = Array.from(xmlParse.getElementsByTagName("measure"));
- state.firstMeasureNumber = measures[0] ? Number(measures[0].getAttribute('number') || 1) : 1;
- const minutes: any = xmlParse.getElementsByTagName("per-minute");
- let speeds: any = []
- for (const minute of minutes) {
- let measureSpeed = minute.textContent ? Number(minute.textContent) : 0;
-
-
-
- if (minute.textContent && measureSpeed) {
- speeds.push(Number(measureSpeed))
- }
-
-
-
-
-
- }
- speeds = [...new Set(speeds)]
- const hasVaryingSpeed = speeds.length > 1 ? true : false
-
- if (state.originSpeed === 0) {
- state.originSpeed = speeds[0] ? speeds[0] : 100;
- state.speed = state.originSpeed;
- }
-
- const metronomeXml = xmlParse.getElementsByTagName('metronome')?.[0]
- const beatUnit = metronomeXml?.getElementsByTagName('beat-unit')?.[0]?.textContent || ''
- if(beatUnit){
- const beatUnitDot = metronomeXml?.getElementsByTagName('beat-unit-dot')?.[0]
- state.speedBeatUnit = beatUnitTo(beatUnit, !!beatUnitDot)
- }
-
- if (speeds.length === 0) {
- ;(window as any).baseMeasureSpeed = state.originSpeed
- } else {
-
- state.originAudioPlayRate = speedBeatTo({unit:state.speedBeatUnit, speed:speeds[0]}, "1/4") / state.originSpeed
- }
- console.log('是否是变速的曲子:',hasVaryingSpeed,speeds)
- let repeats: any = [];
- if (state.partIndex === 999) {
- repeats = Array.from(xmlParse.querySelectorAll('repeat')) || [];
- } else {
- const hasCommon = xmlParse.querySelectorAll('part-name')?.[0]?.textContent === 'common';
- const currentTrackIndex = hasCommon ? state.partIndex + 1 : state.partIndex;
- repeats = Array.from(xmlParse.querySelectorAll('part')?.[currentTrackIndex]?.querySelectorAll('repeat')) || [];
- }
- compatibleXmlPitchVoice(xmlParse);
-
- getComposer(xmlParse);
-
- parseXmlToRepeat(repeats)
-
- if (state.isEvxml) {
- analyzeEvxml(xmlParse, xmlUrl);
- customizationXml(xmlParse);
- }
-
-
-
-
-
-
-
-
- let speed = -1
- let beats = -1;
- let beatType = -1;
-
- let preBeats: number = 4;
- let preBeatType: number = 4;
- let baseDivisions: number = 256;
-
- for (const measure of measures) {
- if (beats === -1 && measure.getElementsByTagName("beats").length) {
- beats = parseInt(measure.getElementsByTagName("beats")[0].textContent || "4");
- }
- if (beatType === -1 && measure.getElementsByTagName("beat-type").length) {
- beatType = parseInt(measure.getElementsByTagName("beat-type")[0].textContent || "4");
- }
- if (speed === -1 && measure.getElementsByTagName('per-minute').length) {
- speed = Number(measure.getElementsByTagName('per-minute')[0]?.textContent)
- }
-
- const currentBeats = measure.getElementsByTagName("beats").length ? measure.getElementsByTagName("beats")[0]?.textContent : preBeats;
- const currentBeatType = measure.getElementsByTagName("beat-type").length ? measure.getElementsByTagName("beat-type")[0]?.textContent : preBeatType;
- preBeats = Number(currentBeats);
- preBeatType = Number(currentBeatType);
- const divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || String(baseDivisions));
- baseDivisions = divisions
-
- if (measure.getElementsByTagName("note").length && state.isEvxml) {
- const noteList = Array.from(measure.getElementsByTagName("note")) || [];
- noteList.forEach((note: any) => {
-
-
-
-
- if (!note.getElementsByTagName("grace").length) {
- if (!note.getElementsByTagName("duration").length || (note.getElementsByTagName("duration").length && note.getElementsByTagName("duration")[0]?.textContent == 0)) {
- measure.removeChild(note);
- }
- }
- });
- }
-
- const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
- if (measure.getElementsByTagName("words").length && state.isEvxml) {
- const wordList = Array.from(measure.getElementsByTagName("words")) || [];
- wordList.forEach((word: any) => {
-
-
- if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
- measure.removeChild(word.parentNode.parentNode);
-
- }
-
-
-
- })
- }
- if (measure.getElementsByTagName("note").length === 0) {
- const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
- if (forwardTimeElement) {
- forwardTimeElement.textContent = "0";
- }
- measure.innerHTML =
- measure.innerHTML +
- `
- <note>
- <rest measure="yes"/>
- <duration>${divisions * beats}</duration>
- <voice>1</voice>
- <type>whole</type>
- </note>`;
- } else if (state.musicRenderType !== 'staff') {
- transferJianNote(measure, divisions, preBeats, preBeatType)
- }
- }
- xmlDocRef.value = xmlParse;
- return new XMLSerializer().serializeToString(xmlParse);
- };
- export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
- const customNoteRealValue = customData.customNoteRealValue;
- const customNoteCurrentTime = customData.customNoteCurrentTime;
- const detailId = state.examSongId + "";
- const partIndex = state.partIndex + "";
-
- let fixtime = 0;
- const allNotes: any[] = [];
- const allNoteId: string[] = [];
- const allMeasures: any[] = [];
- const { originSpeed: baseSpeed } = state;
- let preMeasureNumber = 0;
- const formatRealKey = (realKey: number, detail: any) => {
-
-
-
- const olnyOneIds = ["906"];
- if (olnyOneIds.includes(state.cbsExamSongId)) {
- return detail.measures[0]?.realKey || realKey;
- }
-
- const olnyOneIds2 = ["782", "784"];
- if (olnyOneIds2.includes(state.cbsExamSongId)) {
- const measureNumbers = [14, 16, 30, 32];
- if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
- return allNotes[allNotes.length - 1]?.realKey || realKey;
- }
- }
-
- const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
- if (filterIds.includes(state.cbsExamSongId)) {
- if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
- return detail.measures[0]?.realKey || realKey;
- }
- }
- return realKey;
- };
- if (!osmd.cursor) return [];
- const iterator: any = osmd.cursor.Iterator;
-
- console.time("音符跑完时间");
- let i = 0;
- let si = 0;
- let measures: any[] = [];
- let stepSpeeds: number[] = [];
-
- let difftime = 0;
- let usetime = 0;
- let relaMeasureLength = 0;
- let beatUnit = "quarter";
- let gradualSpeed;
- let gradualChange: GradualChange | undefined;
- let gradualChangeIndex = 0;
- let totalMultipleRestMeasures = 0;
- let multipleRestMeasures = 0;
- let staveNoteIndex = 0;
- let staveIndex = 0;
- let xmlMp3BeatFixTime = 0
- let preNoteEndTime = 0;
- let preNoteMeasureNumber: any = null;
- let currentRealTempo: any = {};
- const _notes = [] as any[];
- if (state.gradualTimes) {
- console.log("后台设置的渐慢小节时间", state.gradual, state.gradualTimes);
- }
- let currentTimeStamp = iterator.currentTimeStamp.RealValue;
- const currentTimes = [] as any[];
- let isSetNextNoteReal = false;
- let differFrom = 0;
-
- let repeatIdx = 0;
-
-
- const firstTrackName = state.combinePartIndexs.length>1 ? state.partListNames[state.combinePartIndexs[0]] : (state.osmd.Sheet.Instruments[0].Name || state.osmd.Sheet.Instruments[0].NameLabel.text || "");
- const currentTrackIndex = state.isCombineRender && state.combinePartIndexs.length > 1 ? state.combinePartIndexs[0] : 0;
- while (!iterator.EndReached) {
-
-
- if (state.isCombineRender) {
- iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
- const trackName = state.isEvxml && state.evxmlAddPartName ? item.parentVoice.parent.IdString || '' : item.parentVoice.parent.Name || '';
- return trackName?.trim() === firstTrackName
- });
- }
-
- if ( ((!state.isCombineRender && state.isSingleMutliTrack) || state.isCombineRender) && iterator.currentVoiceEntries.length) {
- iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
- return item.ParentVoice.voiceId === 1
- });
- }
- let minIndex = 0, elRealValue = 0
- for (let index = 0; index < iterator.currentVoiceEntries.length; index++) {
- const element = iterator.currentVoiceEntries[index];
- if (element.isGrace) {
- if (minIndex == index && minIndex == 0) {
- minIndex = iterator.currentVoiceEntries.length > 1 ? 1 : 0
- }
- continue
- }
- if (element.notes[0].length.realValue < elRealValue) {
- minIndex = index
- }
-
- elRealValue = element.notes[0].length.realValue
- }
- if (minIndex !== 0 && state.isCombineRender && iterator.currentVoiceEntries[minIndex]) {
- iterator.currentVoiceEntries[minIndex].Notes[0].NoteToGraphicalNoteObjectId = iterator.currentVoiceEntries?.[0].Notes[0].NoteToGraphicalNoteObjectId;
- }
- const voiceEntries = iterator.currentVoiceEntries?.[minIndex] ? [iterator.currentVoiceEntries?.[minIndex]] : [];
- let currentVoiceEntries: any[] = [];
-
- let maxNoteNum = 0;
-
- maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
-
-
- if (state.multitrack > 0) {
- currentVoiceEntries = [...iterator.CurrentVoiceEntries];
- } else {
- currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
- return n && n?.ParentVoice?.VoiceId != 1;
- });
- }
- let currentTime = 0;
- let isDouble = false;
- let isMutileSubject = false;
- if (currentVoiceEntries.length && !isSetNextNoteReal) {
- isDouble = true;
- let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
- notes.push(...n.Notes);
- return notes;
- }, [] as any);
- voiceNotes = voiceNotes.filter((note: any) => !note.IsGraceNote)
- voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
- currentTime = voiceNotes?.[0]?.length?.realValue || 0;
- if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
- const min = voiceNotes[0]?.length?.realValue || 0;
- const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
- differFrom = max - min;
- isSetNextNoteReal = differFrom === 0 ? false : true;
- }
- }
-
- if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
- isMutileSubject = true;
- }
- if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
- isDouble = true;
- currentTime = differFrom;
- isSetNextNoteReal = false;
- differFrom = 0;
- }
- currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
- currentTimeStamp = iterator.currentTimeStamp.realValue;
- for (const v of voiceEntries) {
- let note = v.notes[0];
- if (note.IsGraceNote) {
-
- const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace);
- if (!voice) {
- continue;
- }
- note = voice.notes[0];
- }
- note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
-
- if (note?.voiceEntry?.isGrace) {
- isDouble = true;
- let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
- notes.push(...n.notes);
- return notes;
- }, []);
- ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
- currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
- }
- if (state.multitrack > 0 && currentTime > note.length.realValue) {
- currentTime = note.length.realValue;
- }
- note.maxNoteNum = maxNoteNum;
- note.trackIndex = minIndex;
- currentRealTempo = iterator.currentMeasure.tempoExpressions.length ? iterator.currentMeasure.tempoExpressions.find((item: any) => item?.InstantaneousTempo?.isMetronomeMark)?.InstantaneousTempo || currentRealTempo : currentRealTempo;
- const { beatUnit="quarter", dotted=false, tempoInBpm=state.originSpeed } = currentRealTempo
- const speedBeatUnit = beatUnitTo(beatUnit, dotted)
- _notes.push({
- measureNum: note?.sourceMeasure?.MeasureNumberXML,
- note,
- iterator: { ...iterator },
- currentTime,
- isDouble,
- isMutileSubject,
-
-
- measuresTempoInBPM: speedBeatTo({unit: speedBeatUnit || "1/4",speed: tempoInBpm || 0}, `1/4`),
- speedBeatUnit,
- currentRealTempo
- });
- }
- iterator.moveToNextVisibleVoiceEntry(false);
-
- if (iterator.backJumpOccurred) {
- repeatIdx += 1;
- }
- iterator.repeatIdx = repeatIdx;
-
-
- }
-
- const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
- console.log('变速曲子',hasVaryingSpeed, _notes)
- let noteIds: any = [];
-
- for (let { note, iterator, currentTime, isDouble, isMutileSubject, speedBeatUnit, measuresTempoInBPM } of _notes) {
- if (note) {
- if (preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
- si = 0
- }
- if (si === 0 && preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
- preMeasureNumber = note?.sourceMeasure?.MeasureNumberXML
- allMeasures.push(note.sourceMeasure);
- }
-
-
-
-
-
-
-
-
-
- if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
- staveNoteIndex++
- } else {
-
- staveIndex = note.sourceMeasure?.MeasureNumberXML
- staveNoteIndex = 0
- }
- let measureSpeed = note.sourceMeasure.tempoInBPM;
- const { metronomeNoteIndex } = iterator.currentMeasure;
- if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
- measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
- }
-
- let activeVerticalMeasureList: any = [];
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if (state.isCombineRender && note.sourceMeasure.verticalMeasureList.length) {
- note.sourceMeasure.verticalMeasureList = note.sourceMeasure?.verticalMeasureList.filter((item: any) => state.canSelectTracks.includes(item?.parentStaff?.parentInstrument.Name?.trim()))
- }
- activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentTrackIndex]] || [];
-
- if (state.isCombineRender && state.isEvxml && note.sourceMeasure?.verticalMeasureList.length === 0) {
- activeVerticalMeasureList = osmd.GraphicSheet.MeasureList.find((item: any) => item[0]?.MeasureNumber === note.sourceMeasure.MeasureNumberXML) || [];
- }
- let currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
-
- const vmLength = note.sourceMeasure?.verticalMeasureList?.length
- let currentVmIndex = 0;
- let hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
- while (!hasSvgElement && vmLength > 1 && currentVmIndex <= vmLength - 1 && currenrtVfVoices !== null) {
- currentVmIndex += 1;
- activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentVmIndex]] || [];
- currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
- hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
- }
- const { realValue } = iterator.currentTimeStamp;
- const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(
- iterator.currentMeasure.activeTimeSignature,
- iterator.currentMeasure.duration
- );
- let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
- if (customNoteRealValue[i]) {
-
- NoteRealValue = customNoteRealValue[i];
- }
- if (isDouble && currentTime > 0) {
- if (currentTime != NoteRealValue) {
-
- NoteRealValue = currentTime;
- }
- }
-
-
- if (customNoteCurrentTime) {
- if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
-
- NoteRealValue = currentTimes[i + 1];
- }
- }
- let relativeTime = usetime;
-
- if (state.isEvxml && relativeTime < preNoteEndTime - fixtime) {
- relativeTime = preNoteEndTime - fixtime
- }
- let beatSpeed = 0;
-
-
-
-
-
-
-
- beatSpeed = measuresTempoInBPM;
-
- beatSpeed = beatSpeed / state.originAudioPlayRate;
-
- if (i === 0) {
- if(state.isOpenMetronome){
- fixtime += getFixTime(beatSpeed);
- state.fixtime = fixtime;
- }
-
- xmlMp3BeatFixTime = getFixTime(beatSpeed)
-
- }
- let gradualLength = 0;
-
- let speed = measureSpeed ? measureSpeed : baseSpeed;
- gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
- gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
- if (!gradualSpeed || gradualSpeed.length < 2) {
- gradualSpeed = createSpeedInfo(gradualChange, speed);
- }
-
- const measureListIndex = iterator.currentMeasure.measureListIndex;
-
- if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
- const withInRangeNote = state.gradual.find((item, index) => {
- const nextItem: any = state.gradual[index + 1];
- return (
- item[0].measureIndex <= measureListIndex &&
- item[1]?.measureIndex! >= measureListIndex &&
- (!nextItem || nextItem?.[0].measureIndex !== measureListIndex)
- );
- });
- const [first, last] = withInRangeNote || [];
- if (first && last) {
-
- const continuous = last.measureIndex - first.measureIndex;
-
- const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
-
- const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
-
- const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
- if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
- const startTime = state.gradualTimes[first.measureIndex];
- const endTime = state.gradualTimes[last.measureIndex];
- if (startTime && endTime) {
- const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
- const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
- gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
- }
- }
- }
- }
- const _noteLength = NoteRealValue;
-
- let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
-
- const measureLength = vRealValue * 4 * (60 / beatSpeed);
-
-
-
- if (['1788501975122489346','1788502467554750466'].includes(state.cbsExamSongId)) {
- if (i == 13) {
- noteLength = noteLength / 2;
- }
- if (i == 44) {
- noteLength = noteLength * 6;
- }
- if (i == 56) {
- noteLength = noteLength * 4;
- }
- }
- usetime += noteLength;
- relaMeasureLength += noteLength;
- let relaEndtime = noteLength + relativeTime;
-
- const fixedKey = note.fixedKey || 0;
-
-
-
- const filterTickables = currenrtVfVoices?.tickables?.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
- const svgElement = filterTickables?.[staveNoteIndex];
-
-
- if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
- i++
- continue;
- }
-
-
- if (i === 0 && !state.isAppPlay) {
- let _firstMeasureRealValue = 0;
- const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
-
- staffEntries.forEach((_a: any) => {
-
- const matchNote = _a?.sourceStaffEntry?.voiceEntries?.length > 1 ? _a?.sourceStaffEntry?.voiceEntries.find((item: any) => !item.isGrace) : _a?.sourceStaffEntry?.voiceEntries?.[0]
- if (matchNote?.notes?.[0]?.length?.realValue) {
- _firstMeasureRealValue += matchNote.notes[0].length.realValue;
- }
- });
- if (_firstMeasureRealValue < vRealValue) {
-
-
- difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
- }
-
-
-
-
-
-
-
-
-
- if (difftime > 0 && !state.isEvxml) {
- fixtime += difftime;
- state.fixtime = fixtime;
- }
-
- if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
-
-
- }
-
- if (state.isEvxml) {
- fixtime = state.evXmlBeginTime ? state.evXmlBeginTime : fixtime
- state.fixtime = fixtime
- }
- console.log('节拍器时间',fixtime,state.evXmlBeginTime)
- }
- let stave = activeVerticalMeasureList[0]?.stave;
- if (note.sourceMeasure.multipleRestMeasures) {
- totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures;
- multipleRestMeasures = 0;
- }
- if (multipleRestMeasures < totalMultipleRestMeasures) {
- if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
- multipleRestMeasures++;
- } else {
- multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
- }
- } else {
- if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
- multipleRestMeasures = 0;
- totalMultipleRestMeasures = 0;
- } else {
- multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
- }
- }
-
-
-
-
- let evNoteStartTime = 0, evNoteEndTime = 0;
- if (state.isEvxml && note?.noteTimeInfo?.length === 0 && state.xmlHasTimes ) {
-
- let preNoteTImes = allNotes[allNotes.length - 1]?.endtime*1000
- if(!preNoteTImes){
-
- preNoteTImes = (state.evXmlBeginArr.length>0 ? fixtime : Math.max(fixtime - noteLength, 0))*1000
- }
-
- let nextI = i
- let nextNoteTimes
-
- const notesRatio = []
- while (!nextNoteTimes && nextI<_notes.length) {
- notesRatio.push(_notes[nextI].note.length.realValue)
- nextI++
- if(_notes[nextI]?.note){
- nextNoteTimes = fliterNotesTime(_notes[nextI].note, preNoteTImes)
- }
- }
-
- if(!nextNoteTimes){
- nextNoteTimes = preNoteTImes + noteLength*1000
- }
-
- const allowRange = Math.abs(nextNoteTimes - preNoteTImes)< 10;
- if (allowRange) {
- note.maxNoteNum = note.maxNoteNum - 1;
-
- allNotes[allNotes.length - 1].noteLengthTime += noteLength
- i++
- continue;
- }else{
-
- if(notesRatio.length > 1){
- const sum = notesRatio.reduce((acc:number, curr:number) => acc + curr, 0)
- nextNoteTimes = (nextNoteTimes - preNoteTImes) * notesRatio[0] / sum + preNoteTImes
- }
- evNoteEndTime = nextNoteTimes/1000
- evNoteStartTime = preNoteTImes/1000
-
- if(evNoteEndTime - evNoteStartTime > noteLength){
- evNoteEndTime = evNoteStartTime + noteLength
- }
- if (evNoteStartTime) {
- relativeTime = evNoteStartTime - fixtime
- }
- }
- }
- if (state.isEvxml && note?.noteTimeInfo?.length ) {
- let idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0;
-
- if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
- const customRestId = `rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`;
- idx = noteIds.filter((item: any) => item === customRestId)?.length || 0;
- }
- evNoteStartTime = note?.noteTimeInfo[idx]?.begin
- evNoteEndTime = note?.noteTimeInfo[idx]?.end
- if (evNoteStartTime) {
- relativeTime = evNoteStartTime - fixtime
-
- }
-
- }
- svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
-
- if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
- noteIds.push(`rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`)
- }
-
- let hasGraceNote = false;
- if (svgElement?.modifiers?.length) {
- hasGraceNote = svgElement?.modifiers.some((item: any) => item?.attrs?.type === "GraceNoteGroup")
- }
- const filterRepeatIdx = allNotes.filter((item: any) => item.noteId === note.NoteToGraphicalNoteObjectId).length
- const nodeDetail = {
- trackIndex: note.trackIndex,
- isStaccato: note.voiceEntry.isStaccato(),
- isRestFlag: note.isRestFlag,
- noteId: note.NoteToGraphicalNoteObjectId === undefined ? `restNote${note.sourceMeasure.MeasureNumberXML}` : note.NoteToGraphicalNoteObjectId,
-
- measureListIndex: note.sourceMeasure.measureListIndex,
- MeasureNumberXML: note.sourceMeasure.MeasureNumberXML,
- _noteLength: _noteLength,
- svgElement: svgElement,
- frequency: note?.pitch?.frequency || -1,
- nextFrequency: note?.pitch?.nextFrequency || -1,
- prevFrequency: note?.pitch?.prevFrequency || -1,
- difftime,
- octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
- speed,
- beatSpeed,
- i,
- si,
- stepSpeeds,
- measureOpenIndex: allMeasures.length - 1,
- measures,
- tempoInBPM: note.sourceMeasure.tempoInBPM,
- measureLength,
- relaMeasureLength,
- id: svgElement?.attrs.id,
- hasGraceNote,
- note: note.halfTone + 12,
- fixtime,
- relativeTime: retain(relativeTime),
- time: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + fixtime),
- endtime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + fixtime),
- relaEndtime: retain(relaEndtime),
- realValue,
- halfTone: note.halfTone,
- noteElement: note,
- fixedKey,
- realKey: 0,
- duration: 0,
- formatLyricsEntries: formatLyricsEntries(note),
- stave,
- firstVerticalMeasure: activeVerticalMeasureList[0],
- noteLength: 1,
-
-
- speedBeatUnit,
- multipleRestMeasures: multipleRestMeasures,
- totalMultipleRestMeasures,
- measureSpeed,
- maxNoteNum: note.maxNoteNum,
-
- repeatIdx: filterRepeatIdx,
- noteLengthTime: noteLength,
- xmlNoteTime: 0,
- xmlNoteEndTime: 0,
- xmlMp3BeatFixTime,
- notBeatFixtime: state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime,
- notBeatTime: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)),
- notBeatEndTime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)),
- frequencyList: [note?.pitch?.frequency || -1],
- };
-
-
-
-
-
-
-
-
-
-
- if (note.voiceEntry.notes.length > 1) {
- note.voiceEntry.notes.forEach((cnote: any) => {
- if (cnote?.IsChordNote && cnote?.pitch?.frequency) {
- nodeDetail.frequencyList.push(cnote.pitch.frequency)
- }
- })
- }
- const firstRepeatNodeId = allNotes.find((item: any) => item.MeasureNumberXML === state.timegapRepeatMeasureIndex)?.noteId || 0;
- if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === state.timegapRepeatMeasureIndex && nodeDetail.noteId === firstRepeatNodeId) {
- const currentWaitTime = state.evXmlBeginArr[nodeDetail.repeatIdx] || 0;
- nodeDetail.time = nodeDetail.time + currentWaitTime;
- nodeDetail.endtime = nodeDetail.endtime + currentWaitTime;
- usetime = usetime + currentWaitTime;
- relativeTime = relativeTime + currentWaitTime;
- }
- nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
- nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
- let tickables = currenrtVfVoices?.tickables || [];
- if ([121].includes(state.subjectId)) {
- tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
- }
-
-
-
- tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
- let maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
-
- if (note.isRestFlag && maxNum === 0) {
- maxNum = note.maxNoteNum;
- }
- nodeDetail.noteLength = maxNum || 1;
- allNotes.push(nodeDetail);
- allNoteId.push(nodeDetail.id);
- if ( measures.some((item: any) => item.MeasureNumberXML !== nodeDetail.MeasureNumberXML) ) {
- measures = [];
- measures.push(nodeDetail);
- nodeDetail.measures = measures;
- } else {
- measures.push(nodeDetail);
- }
-
- if (si < maxNum - 1) {
- si++;
- } else {
- si = 0;
- relaMeasureLength = 0;
- measures = [];
- }
- preNoteEndTime = nodeDetail.endtime;
- }
- preNoteMeasureNumber = note?.sourceMeasure?.MeasureNumberXML;
- i++;
- }
-
- const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => Object.assign(item,{i:index}));
-
-
-
- let xmlNoteTime = 0
- sortArray.map(item => {
- const noteLengthTime = item.noteLengthTime
- item.xmlNoteTime = retain(xmlNoteTime)
- item.xmlNoteEndTime = retain(xmlNoteTime + noteLengthTime)
- xmlNoteTime += noteLengthTime
- })
- console.timeEnd("音符跑完时间");
- try {
- osmd.cursor.reset();
- } catch (error) {}
- return sortArray;
- };
- export const getNoteByMeasuresSlursStart = (note: any) => {
- let activeNote = note;
- let tieNote;
- if (note.noteElement.tie && note.noteElement.tie.StartNote) {
- tieNote = note.noteElement.tie.StartNote;
- }
- if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
- const arr: any = []
- for (const note of state.times) {
- if (tieNote === note.noteElement) {
- arr.push(note)
- }
- }
- if (arr.length) {
- return arr.find((n: any) => n.i === (note.i - 1)) || arr[0]
- }
- }
- return activeNote;
- };
- const getComposer = (xmlParse: any) => {
- const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
- for (const creator of creators) {
- if (creator && creator.getAttribute('type') === 'composer' && !state.musicComposer) {
- state.musicComposer = creator.textContent?.trim() || '';
- }
- if (creator && creator.getAttribute('type') === 'lyricist' && !state.musicLyricist) {
- state.musicLyricist = creator.textContent?.trim() || '';
- }
- }
- }
- const parseXmlToRepeat = (repeats: any) => {
- if (!repeats.length) return
- let repeatInfo: any = []
-
- let start = 0, end = 0
- for (let i = 0; i < repeats.length; i++) {
- const element = repeats[i];
- const direction = element.getAttribute('direction')
- let parentElement = element.parentNode
- while (parentElement && parentElement.tagName !== 'measure') {
- parentElement = parentElement.parentNode
- }
- let notesNumber = parentElement.getAttribute('number')
- notesNumber = notesNumber ? Number(notesNumber) : 0
- if (direction === 'forward') {
- start = notesNumber
- } else if (direction === 'backward') {
- end = notesNumber
- repeatInfo.push({
- start,
- end
- })
- }
- }
- state.repeatInfo = repeatInfo
-
- }
- export const verifyCanRepeat = (startNum: number, endNum: number) => {
- let repeatIdx = -1
- if (state.repeatInfo.length) {
- for (let i = state.repeatInfo.length - 1; i >= 0; i--) {
- const { start, end } = state.repeatInfo[i];
- if (startNum <= start && endNum >= end) {
- repeatIdx = i
- return {
- repeatIdx,
- canRepeat: true
- }
- break;
- }
- }
- return {
- repeatIdx,
- canRepeat: false
- }
- } else {
- return {
- repeatIdx,
- canRepeat: false
- }
- }
- }
- const customizationXml = (xmlParse: any) => {
- const credits: any = Array.from(xmlParse.querySelectorAll('credit'));
- const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
- const graces: any = Array.from(xmlParse.querySelectorAll('grace'));
- const measures: any[] = Array.from(xmlParse.getElementsByTagName("measure"));
- const notes: any[] = Array.from(xmlParse.getElementsByTagName("note"));
-
- let maxLyricNum = 0, maxTimeNum = 0;
- if (notes && notes.length) {
- for (const note of notes) {
- if (maxLyricNum < note.getElementsByTagName("lyric").length) {
- maxLyricNum = note.getElementsByTagName("lyric").length
- }
- if (maxTimeNum < note.getElementsByTagName("time").length) {
- maxTimeNum = note.getElementsByTagName("time").length
- }
- }
- }
- state.maxLyricNum = Math.max(maxLyricNum, maxTimeNum);
-
- ;(window as any).DYCustomRepeatCount = state.maxLyricNum;
- console.log('歌词次数',maxLyricNum)
- if (credits && credits.length) {
- for (const credit of credits) {
- if (credit.getElementsByTagName("credit-type")?.[0]?.textContent === 'lyricist') {
- const creditWord = credit.getElementsByTagName("credit-words")
- creditWord?.[0].setAttribute('justify', 'right')
- }
- }
- }
- if (creators && creators.length) {
- for (const creator of creators) {
- if (creator.getAttribute('type') === 'lyricist') {
-
- }
-
- }
- }
-
- if (graces && graces.length) {
- for (const grace of graces) {
- grace?.setAttribute('slash','yes');
-
- }
- }
-
- for (const measure of measures) {
- const hasNote = measure.getElementsByTagName("note").length;
- const hasSegno = measure.getElementsByTagName("segno").length;
- const sounds = Array.from(measure.getElementsByTagName("sound"));
- const hasSoundSegno = sounds.some((item: any) => item.getAttribute('segno') === 'segno' );
- if (!hasNote && hasSegno && hasSoundSegno) {
- const parent = measure.parentNode;
- parent.removeChild(measure);
- }
- }
-
- if (maxLyricNum > 1) {
- const hasRepeat = xmlParse.querySelectorAll('repeat').length > 0;
- if (!hasRepeat) {
- const parts = xmlParse.querySelectorAll('score-partwise>part')
- if (parts.length) {
- for (const part of parts) {
- const currentMeasures = part.querySelectorAll('measure').length ? Array.from(part.querySelectorAll('measure')) : [];
- const lastMeasure: any = currentMeasures.last();
- if (lastMeasure?.getElementsByTagName('barline').length) {
- const barlineDom = lastMeasure?.getElementsByTagName('barline')[0]
- barlineDom.innerHTML = barlineDom.innerHTML + `<repeat direction="backward" />`;
- } else {
- lastMeasure.innerHTML = lastMeasure.innerHTML + `
- <barline location="right">
- <bar-style>light-heavy</bar-style>
- <repeat direction="backward" />
- </barline>`
- }
-
- }
- }
- }
- }
- }
- const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
-
- const xmlNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('num');
- const denNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('den');
- const xmlNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('num');
- const denNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('den');
- const timeGaps: any = xmlParse.getElementsByTagName("timegap")?.length ? Array.from(xmlParse.getElementsByTagName("timegap")?.[0]?.getElementsByTagName("values")?.[0]?.getElementsByTagName("item")) : [];
- state.xmlHasTimes = !!xmlParse.getElementsByTagName("times")?.length
-
- const firstMeasure = xmlParse.getElementsByTagName("measure")[0];
- if (firstMeasure) {
- const firstNoteBeginTime = firstMeasure.getElementsByTagName("times")[0]?.getElementsByTagName("time")[0]?.getAttribute('begin');
- state.evXmlBeginTime = firstNoteBeginTime ? firstNoteBeginTime / 1000 : xmlNum ? 60 / state.originSpeed * xmlNum * 4/denNum : 0;
- state.secondEvXmlBeginTime = firstNoteBeginTime ? 0 : xmlNum2 ? 60 / state.originSpeed * xmlNum2 * 4/denNum2 : 0;
- const hasTimeGap = state.xmlHasTimeGap = xmlParse.getElementsByTagName("timegap").length > 0;
- const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
- if (timeGaps && timeGaps.length && !firstNoteBeginTime) {
-
- const startRepeat = Array.from(xmlParse.getElementsByTagName("repeat") || []).filter((item: any) => item?.getAttribute('direction') === 'forward')
- const firstRepeat: any = startRepeat?.length ? startRepeat[0] : null;
- if (firstRepeat) {
- let parentElement = firstRepeat?.parentNode
- while (parentElement && parentElement.tagName !== 'measure') {
- parentElement = parentElement.parentNode
- }
- state.timegapRepeatMeasureIndex = parentElement?.getAttribute('number') ? Number(parentElement?.getAttribute('number')) : 1;
- }
- for (const timeGap of timeGaps) {
- const num: any = timeGap?.getAttribute('num'), den: any = timeGap?.getAttribute('den');
- const startTime = num ? 60 / state.originSpeed * num * 4/den : 0;
- state.evXmlBeginArr.push(startTime)
- }
- }
- console.log('🚀 ~ evxml解析','有timegap:',hasTimeGap,'有times:',hasTimes,'timegap集合',state.evXmlBeginArr,'第一个timegap',state.evXmlBeginTime)
- }
-
-
-
-
- }
- export const compatibleXmlPitchVoice = (xmlParse: any) => {
- const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
- const partListNames = partNames.filter((item: any) => item?.textContent?.trim().toLocaleUpperCase() !== "COMMON");
- if (partListNames.length == 1) {
- const instrumentNames = Array.from(xmlParse.getElementsByTagName('instrument-name')) || [];
-
- const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
-
-
- let xmlNeedAdjustVoice = false;
- switch (state.musicalCodeId) {
- case 37:
- case 38:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('tenor recorder') ? true : false
- break;
- case 33:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('panpipes') ? true : false
- break;
- case 34:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('ocarina') ? true : false
- break;
- case 35:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('woodwind') ? true : false
- break;
- case 39:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('whistling') ? true : false
- break;
- default:
- xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') ? true : false
- break;
- }
-
-
- (window as any).xmlNeedAdjustVoice = true
- }
- }
- function fliterNotesTime(note:any, preTime:number):undefined|number {
-
- if(note?.noteTimeInfo?.length){
- const timeObj = note?.noteTimeInfo.find((value:any) => {
- const beginTime = value?.begin*1000 || 0
- return beginTime > preTime || Math.abs(beginTime - preTime)< 10
- })
- return timeObj?.begin*1000
- }else{
- return undefined
- }
- }
|