12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565 |
- import dayjs from "dayjs";
- import duration from "dayjs/plugin/duration";
- import state, { customData } from "/src/state";
- import { browser } from "../utils/index";
- import {
- isSpecialMark,
- isSpeedKeyword,
- Fraction,
- SourceMeasure,
- isGradientWords,
- GRADIENT_SPEED_RESET_TAG,
- StringUtil,
- OpenSheetMusicDisplay,
- } from "/osmd-extended/src";
- import { GradualChange, speedInfo } from "./calcSpeed";
- const browserInfo = browser();
- dayjs.extend(duration);
- /**
- * 需要隐藏的中文速度文本
- */
- const hideSpeedWords: string[] = ["中速"];
- /**
- * 获取节拍器的时间
- * @param speed 速度
- * @param firstMeasure 曲谱第一个小节
- * @returns 节拍器的时间
- */
- 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 = duration.beatUnit || "quarter";
- // if (state.repeatedBeats) {
- // // 音频制作问题仅2拍不重复
- // numerator = numerator === 2 ? 4 : numerator;
- // } else if (numerator === 2 && denominator === 4) {
- // numerator = 4
- // }
- // 重复节拍,拍数*2进行计算
- if (state.repeatedBeats) {
- numerator = numerator*2;
- }
- // console.log('diff', speed, duration, formatBeatUnit(beatUnit), denominator, numerator, (numerator / denominator))
- 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;
- };
- /** 按照dorico的渐快渐慢生成对应的速度 */
- 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]}`;
- }
- // console.log(`1970-01-01 00:${result}0`)
- 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;
- };
- /** 根据 noteElement 获取note */
- export const getParentNote = (note: any) => {
- let parentNote;
- if (note) {
- // time = activeNote.time
- for (const n of state.times) {
- if (note === n.noteElement) {
- // console.log(note)
- 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";
- for (const item of TempoExpressions) {
- beatUnit = item.InstantaneousTempo.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 {
- // 弱起第一小节duration不对
- return activeTimeSignature;
- }
- export function formatBeatUnit(beatUnit: string) {
- let multiple = 4;
- switch (beatUnit) {
- case "1024th":
- // bpm = bpm;
- multiple = 1024;
- break;
- case "512th":
- // divisionsFromNote = (noteDuration / 4) * 512;
- multiple = 512;
- break;
- case "256th":
- // divisionsFromNote = (noteDuration / 4) * 256;
- multiple = 256;
- break;
- case "128th":
- // divisionsFromNote = (noteDuration / 4) * 128;
- multiple = 128;
- break;
- case "64th":
- // divisionsFromNote = (noteDuration / 4) * 64;
- multiple = 64;
- break;
- case "32nd":
- // divisionsFromNote = (noteDuration / 4) * 32;
- multiple = 32;
- break;
- case "16th":
- // divisionsFromNote = (noteDuration / 4) * 16;
- multiple = 16;
- break;
- case "eighth":
- // divisionsFromNote = (noteDuration / 4) * 8;
- multiple = 8;
- break;
- case "quarter":
- multiple = 4;
- break;
- case "half":
- // divisionsFromNote = (noteDuration / 4) * 2;
- multiple = 2;
- break;
- case "whole":
- // divisionsFromNote = (noteDuration / 4);
- multiple = 1;
- break;
- case "breve":
- // divisionsFromNote = (noteDuration / 4) / 2;
- multiple = 0.5;
- break;
- case "long":
- // divisionsFromNote = (noteDuration / 4) / 4;
- multiple = 0.25;
- break;
- case "maxima":
- // divisionsFromNote = (noteDuration / 4) / 8;
- multiple = 0.125;
- break;
- default:
- break;
- }
- return multiple;
- }
- /** 根据音符单位,速度,几几拍计算正确的时间 */
- export function getTimeByBeatUnit(beatUnit: string, bpm: number, denominator: number) {
- return (denominator / formatBeatUnit(beatUnit)) * bpm;
- }
- export type CustomInfo = {
- showSpeed: boolean;
- parsedXML: string;
- };
- /** 从xml中获取自定义信息,并删除多余的字符串 */
- export const getCustomInfo = (xml: string): CustomInfo => {
- const data = {
- showSpeed: true,
- parsedXML: xml,
- };
- const xmlParse = 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;
- };
- /**
- * 添加第一分谱信息至当前分谱
- * @param ele 需要插入的元素
- * @param fitstParent 合奏谱第一个分谱
- * @param parent 需要添加的分谱
- */
- 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;
- }
- }
- }
- }
- // console.log(noteIndex, parent)
- };
- /**
- * 检查传入文字是否为重复关键词
- * @param text 总谱xml
- * @returns 是否是重复关键词
- */
- 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): string => {
- if (!xml) return "";
- // console.log('原始xml')
- const detailId = state.examSongId + "";
- const xmlParse = 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 firstTimeInfo = parts[0]?.getElementsByTagName('metronome')[0]?.parentElement?.parentElement?.cloneNode(true)
- 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];
- // console.log(visiblePartInfo, partIndex)
- // 根据后台已选择的分轨筛选出能切换的声轨
- state.partListNames = partListNames;
- // console.log('分轨名称',state.partListNames)
- 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;
- // console.log(parentMeasure)
- if (parentMeasure && metronomesIndex > -1) {
- const index = firstMeasures.indexOf(parentMeasure);
- const activeMeasure = part.getElementsByTagName("measure")[index];
- setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
- }
- });
- /** word比较特殊需要精确到note位置 */
- 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];
- // 找当前小节是否包含word标签
- const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
- // 遍历word标签,检查是否和第一小节重复,如果有重复则不平移word
- 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);
- }
- }
- }
- }
- });
- /** word比较特殊需要精确到note位置 */
- 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;
- // console.log(rehearsal)
- if (parentMeasure) {
- const index = firstMeasures.indexOf(parentMeasure);
- part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
- // console.log(index, parentMeasure, firstMeasures.indexOf(parentMeasure))
- }
- });
- } else {
- words.forEach((word, idx) => {
- const text = word.textContent || "";
- // if (idx == 0 && text) {
- // word.textContent = '测试一下'
- // word.setAttribute('default-y',60)
- // word.setAttribute('margin-left',300)
- // word.setAttribute('y',300)
- // word.outerHTML = '<words default-x="155" default-y="100" justify="right" valign="middle" font-family="SimHei" font-style="normal" font-size="11.9365" font-weight="normal">哈哈哈哈哈</words>'
- // }
- 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) {
- 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);
- }
- });
- }
- // console.log(xmlParse)
- return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
- };
- export const onlyVisible2 = (xml: string): string => {
- if (!xml) return "";
- // console.log('原始xml')
- const detailId = state.examSongId + "";
- const xmlParse = 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() || "");
- state.partListNames = partListNames;
- Array.from(partList).forEach((part) => {
- let partListName = part.getElementsByTagName("part-name")?.[0]?.textContent?.trim();
- if (!state.canSelectTracks.includes(partListName)) {
- part.parentNode?.removeChild(part);
- }
- });
- // console.log(xmlParse)
- 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;
- };
- /** 根据ID获取最顶级ID */
- 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;
- };
- /** 格式化曲谱
- * 1.全休止符的小节,没有音符默认加个全休止符
- */
- export const formatXML = (xml: string, xmlUrl?: string): string => {
- if (!xml) return "";
-
- const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
- const measures = Array.from(xmlParse.getElementsByTagName("measure"));
- const minutes: any = xmlParse.getElementsByTagName("per-minute");
- let speeds: any = []
- for (const minute of minutes) {
- if (minute.textContent && !!Number(minute.textContent)) {
- speeds.push(Number(minute.textContent))
- }
- }
- speeds = [...new Set(speeds)]
- const hasVaryingSpeed = speeds.length > 1 ? true : false
- // 如果后台没有设置速度,默认取xml速度,如果xml也没有速度,默认赋值100
- if (state.originSpeed === 0) {
- state.originSpeed = speeds[0] ? speeds[0] : 100;
- state.speed = state.originSpeed;
- }
- // 如果谱面和小节都没有打速度,osmd设置的小节速度默认取后台设置的速度
- if (speeds.length === 0) {
- ;(window as any).baseMeasureSpeed = state.originSpeed
- } else {
- state.originAudioPlayRate = speeds[0] / state.originSpeed
- }
- console.log('是否是变速的曲子:',hasVaryingSpeed,speeds)
- const repeats: any = Array.from(xmlParse.querySelectorAll('repeat'));
- compatibleXmlPitchVoice(xmlParse);
- // 获取作词、作曲家
- getComposer(xmlParse);
- // 处理重复小节信息
- parseXmlToRepeat(repeats)
- // 解析处理evxml
- if (state.isEvxml) {
- analyzeEvxml(xmlParse, xmlUrl);
- customizationXml(xmlParse);
- }
- // const words: any = xmlParse.getElementsByTagName("words");
- // for (const word of words) {
- // if (word && word.textContent?.trim() === "筒音作5") {
- // word.setAttribute('y',260)
- // word.outerHTML = '<words id="test-word" default-x="805" default-y="100" x="200" justify="right" valign="middle" font-family="SimHei" font-style="normal" font-size="11.9365" font-weight="normal">筒音作5</words>'
- // }
- // }
- // console.log(11111,Array.from(xmlParse.getElementsByTagName("staffline")),Array.from(xmlParse.getElementsByTagName("words")))
- let speed = -1
- let beats = -1;
- let beatType = -1;
- // 小节中如果没有节点默认为休止符
- 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 divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || "256");
- // 如果note节点里面有space节点,并且没有duration节点,代表这是一个空白节点,需要删除
- if (measure.getElementsByTagName("note").length && state.isEvxml) {
- const noteList = Array.from(measure.getElementsByTagName("note")) || [];
- noteList.forEach((note: any) => {
- // if (note.getElementsByTagName("space").length && !note.getElementsByTagName("duration").length) {
- // measure.removeChild(note);
- // }
- // 非倚音音符
- 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) => {
- // TODO:删除妙极客曲子无意义的words
- // wordArr?.push(word?.textContent)
- if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
- measure.removeChild(word.parentNode.parentNode);
- // deleteWordArr?.push(word?.textContent)
- }
- // if(hideSpeedWords.includes(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>`;
- }
- }
- 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 = browserInfo.huawei ? 0.08 : 0; //getFixTime()
- const allNotes: any[] = [];
- const allNoteId: string[] = [];
- const allMeasures: any[] = [];
- const { originSpeed: baseSpeed } = state;
- let preMeasureNumber = 0;
- const formatRealKey = (realKey: number, detail: any) => {
- // 不是管乐迷, 不处理
- // if (state.appName !== "GYM") return realKey;
- // 长笛的LEVEL 2-5-1条练习是泛音练习,以每小节第一个音的指法为准,高音不变变指法。
- const olnyOneIds = ["906"];
- if (olnyOneIds.includes(state.cbsExamSongId)) {
- return detail.measures[0]?.realKey || realKey;
- }
- // 圆号的LEVEL 2-5条练习是泛音练习,最后四小节指法以连音线第一个小节为准
- 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;
- }
- }
- // 2-6 第三小节指法按照第一个音符显示
- 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.log("🚀 ~ iterator:", 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 xmlNoteTime = 0 // xml上面的音符时间
- let xmlMp3BeatFixTime = 0 // xml上节拍器的时间
- let preNoteEndTime = 0; // 上一个音符的结束时间
- 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 testIdx = 0;
- let repeatIdx = 0; // 循环的次数
- while (!iterator.EndReached) {
- // console.log({ ...iterator });
- /** 多声轨合并显示,当前音符的时值取所有声轨中的最小值 */
- 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
- }
- const voiceEntries = iterator.currentVoiceEntries?.[minIndex] ? [iterator.currentVoiceEntries?.[minIndex]] : [];
- let currentVoiceEntries: any[] = [];
- // 多分轨,当前小节最大音符数量
- let maxNoteNum = 0;
- // iterator.currentMeasure?.verticalMeasureList?.forEach((item: any) => maxNoteNum = Math.max(maxNoteNum, item?.staffEntries?.length || 0))
- maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
- // console.log(iterator.currentMeasure.MeasureNumberXML,maxNoteNum,iterator.currentMeasure?.verticalSourceStaffEntryContainers.length)
- // 单声部多声轨
- 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);
- 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
- _notes.push({
- note,
- iterator: { ...iterator },
- currentTime,
- isDouble,
- isMutileSubject,
- measuresTempoInBPM: note?.sourceMeasure?.tempoInBPM
- });
- }
- iterator.moveToNextVisibleVoiceEntry(false);
- // 从头开始循环,repeatIdx标记+1
- if (iterator.backJumpOccurred) {
- repeatIdx += 1;
- }
- iterator.repeatIdx = repeatIdx;
- // console.log('小节',testIdx,iterator.repeatIdx,iterator.EndReached,iterator.currentMeasureIndex,iterator.backJumpOccurred,iterator.forwardJumpOccurred)
- // testIdx += 1;
- }
- // 是否是变速的曲子
- const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
- console.log('变速曲子',hasVaryingSpeed, _notes)
- let noteIds: any = [];
- // let voicesBBox: any = null;
- for (let { note, iterator, currentTime, isDouble, isMutileSubject } 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 (si === 0 && state.isSpecialBookCategory) {
- for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
- if (expression?.InstantaneousTempo?.beatUnit) {
- // 取最后一个有效的tempo
- beatUnit = expression.InstantaneousTempo.beatUnit;
- }
- }
- }
- // 判断是否是同一小节
- if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
- staveNoteIndex++
- } else {
- // staveIndex不同,重新赋值
- 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 = [];
- /**
- * bug: #9959
- * 多分轨合并展示,第一分轨又可能获取不到对应的音符,需要在当前小节中音符最多的分轨中去查找音符
- */
- // if (state.isCombineRender) {
- // const allTrackList = note.sourceMeasure.verticalMeasureList;
- // let maxIdx = 0, maxNote = 0;
- // allTrackList.forEach((item: any, index: number) => {
- // if (item?.vfVoices['1']?.tickables?.length > maxNote) {
- // maxIdx = index
- // maxNote = item?.vfVoices['1']?.tickables?.length
- // }
- // })
- // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[maxIdx]] || [];
- // } else {
- // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
- // }
-
- activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
- /**
- * TODO:多分轨合并的小节,音符可能没有id,此时就去其它分轨找
- */
- const vmLength = note.sourceMeasure?.verticalMeasureList?.length
- let currentVmIndex = 0;
- let hasSvgElement = activeVerticalMeasureList[0]?.vfVoices['1']?.tickables[staveNoteIndex];
- while (!hasSvgElement && vmLength > 1 && currentVmIndex <= vmLength - 1) {
- currentVmIndex += 1;
- activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentVmIndex]] || [];
- hasSvgElement = activeVerticalMeasureList[0]?.vfVoices['1']?.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]) {
- // console.log(NoteRealValue, customNoteRealValue[i])
- NoteRealValue = customNoteRealValue[i];
- }
- if (isDouble && currentTime > 0) {
- if (currentTime != NoteRealValue) {
- // console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
- NoteRealValue = currentTime;
- }
- }
- // note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
- // 管乐迷,按自定义按读取到的音符时值
- if (customNoteCurrentTime) {
- if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
- // console.log(NoteRealValue, currentTimes[i + 1])
- NoteRealValue = currentTimes[i + 1];
- }
- }
- let relativeTime = usetime;
- // 妙极客的曲子,修复有的音符有times,有的音符没有times导致的,累计时长错误问题
- if (state.isEvxml && relativeTime < preNoteEndTime - fixtime) {
- relativeTime = preNoteEndTime - fixtime
- }
- let beatSpeed = 0;
- // 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度,否则mp3速度不对
- if (measureSpeed !== baseSpeed && !hasVaryingSpeed) {
- beatSpeed = baseSpeed || measureSpeed || 100
- } else {
- beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
- }
- // let beatSpeed = measureSpeed || baseSpeed
- // 如果有节拍器,需要将节拍器的时间算出来
- if (i === 0) {
- if(state.isOpenMetronome){
- fixtime += getFixTime(beatSpeed);
- state.fixtime = fixtime;
- }
- // 存储mp3节拍器时间
- xmlMp3BeatFixTime = getFixTime(beatSpeed)
- // console.log("fixtime:", fixtime, '速度:', beatSpeed, "state.isSpecialBookCategory:", state.isSpecialBookCategory, 'state.isOpenMetronome:', state.isOpenMetronome);
- }
- // console.log(getTimeByBeatUnit(beatUnit, measureSpeed, iterator.currentMeasure.activeTimeSignature.Denominator))
- let gradualLength = 0;
- let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
- gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
- gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
- if (!gradualSpeed || gradualSpeed.length < 2) {
- gradualSpeed = createSpeedInfo(gradualChange, speed);
- }
- // console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
- 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;
- }
- }
- }
- } else if (state.appName === "GYM" && gradualChange && gradualSpeed && (gradualChange.startXmlNoteIndex === si || gradualChangeIndex > 0)) {
- const startSpeed = gradualSpeed[0] - (gradualSpeed[1] - gradualSpeed[0]);
- const { resetXmlNoteIndex, endXmlNoteIndex } = gradualChange;
- const noteDiff = endXmlNoteIndex;
- let stepSpeed = (gradualSpeed[gradualSpeed.length - 1] - startSpeed) / noteDiff;
- stepSpeed = note.DotsXml ? stepSpeed / 1.5 : stepSpeed;
- if (gradualChangeIndex < noteDiff) {
- const tempSpeed = Math.ceil(speed + stepSpeed * gradualChangeIndex);
- let tmpSpeed = getTimeByBeatUnit(beatUnit, tempSpeed, iterator.currentMeasure.activeTimeSignature.Denominator);
- const maxLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
- // speed += stepSpeeds.reduce((a, b) => a + b, 0)
- speed += Math.ceil(stepSpeed * (gradualChangeIndex + 1));
- tmpSpeed = getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator);
- const minLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
- gradualLength = (maxLength + minLength) / 2;
- } else if (resetXmlNoteIndex > gradualChangeIndex) {
- speed = allNotes[i - 1]?.speed;
- }
- beatSpeed =
- (state.isSpecialBookCategory ? getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator) : baseSpeed) || 1;
- const isEnd = !(gradualChangeIndex < noteDiff) && !(resetXmlNoteIndex > gradualChangeIndex);
- gradualChangeIndex++;
- if (isEnd) {
- gradualChangeIndex = 0;
- gradualChange = undefined;
- gradualSpeed = undefined;
- stepSpeeds = [];
- }
- }
- const _noteLength = NoteRealValue;
- // 当前音符的持续时长,当前音符的RealValue值*拍数*(60/后台设置的基准速度)
- let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
- // 小节时长
- const measureLength = vRealValue * vDenominator * (60 / beatSpeed);
- // console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
- // console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
- /**
- * TODO:摇篮曲-人音-排箫(1788501975122489346),第12小节音符持续时间特殊处理
- */
- 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;
- // console.log('relaEndtime',noteLength, relativeTime)
- const fixedKey = note.fixedKey || 0;
- // const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
- const svgElement = activeVerticalMeasureList[0]?.vfVoices['1']?.tickables[staveNoteIndex];
- // console.log('si',si,i)
- // console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
- if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
- continue;
- }
- // console.log(iterator.currentMeasure)
- // 如果是弱起就补齐缺省的时长,midi音频不需要考虑弱起
- if (i === 0 && !state.isAppPlay) {
- let _firstMeasureRealValue = 0;
- const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
- //计算第一个小节里面的音符时值是否等于整个小节的时值
- staffEntries.forEach((_a: any) => {
- if (_a?.sourceStaffEntry?.voiceEntries?.[0]?.notes?.[0]?.length?.realValue) {
- _firstMeasureRealValue += _a.sourceStaffEntry.voiceEntries[0].notes[0].length.realValue;
- }
- });
- if (_firstMeasureRealValue < vRealValue) {
- // console.log(_firstMeasureRealValue, vRealValue)
- // 如果是弱起,将整个小节的时值减去该小节所有音符相加的时值,就是缺省的时值
- difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
- }
- /**
- * 管乐迷,部分弱起的曲目,mp3制作不标准,没有按照补齐弱起后的时间进行制作,需要单独处理
- * 2670
- */
- if (["2670"].includes(state.cbsExamSongId)) {
- // fixtime -= _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
- } else {
- if (difftime > 0) {
- fixtime += difftime;
- state.fixtime = fixtime;
- }
- }
- // 管乐迷 diff获取不准确时, 弱起补齐
- if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
- // difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
- // fixtime += difftime;
- }
- // 如果是evxml,fixtime取读取xml的值
- 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) {
- multipleRestMeasures++;
- } else {
- multipleRestMeasures = 0;
- totalMultipleRestMeasures = 0;
- }
- // console.log(note.tie)
- // console.log('👀看看endtime', duration, relaEndtime, fixtime, i)
- // console.log('频率',note?.pitch?.frequency,i)
- /**
- * evxml的曲子,如果曲谱xml中带有times信息,则音符时值优先取times中的值
- */
- let evNoteStartTime = 0, evNoteEndTime = 0;
- if (state.isEvxml && note?.noteTimeInfo?.length) {
- const idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0
- evNoteStartTime = note?.noteTimeInfo[idx]?.begin
- evNoteEndTime = note?.noteTimeInfo[idx]?.end
- if (evNoteStartTime) {
- relativeTime = evNoteStartTime - fixtime
- // usetime = evNoteStartTime - fixtime
- }
- // usetime = evNoteStartTime - fixtime
- }
- svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
- const nodeDetail = {
- isStaccato: note.voiceEntry.isStaccato(),
- isRestFlag: note.isRestFlag,
- noteId: note.NoteToGraphicalNoteObjectId,
- measureListIndex: note.sourceMeasure.measureListIndex,
- MeasureNumberXML: note.sourceMeasure.MeasureNumberXML, // 当前的小节数,(从1开始)
- _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,
- note: note.halfTone + 12, // see issue #224
- 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,
- osdmContext: osmd,
- speedbeatUnit: beatUnit,
- multipleRestMeasures: multipleRestMeasures, // 当前合并小节的索引,从1开始到当前的totalMultipleRestMeasures结束,
- totalMultipleRestMeasures, // 当前小节总的合并小节数
- measureSpeed, // 小节速度
- maxNoteNum: note.maxNoteNum, // 当前小节音符最多的分轨的音符数量
- repeatIdx: iterator.repeatIdx || 0, // 标记是第几遍循环,从0开始
- xmlNoteTime: retain(xmlNoteTime), // xml上音符开始时间 唱名用
- xmlNoteEndTime: retain(xmlNoteTime + noteLength), //xml上音符结束时间 唱名用
- xmlMp3BeatFixTime, //xml上节拍器的时间
- notBeatFixtime: state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime, // 不含节拍器的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)) // 不含节拍器的 音符结束时间
- };
- xmlNoteTime += noteLength
- // 如果是妙极客的曲子,并且第二遍循环播放需要等待时间,并且是第二遍循环的第一个小节的第一个音符
- // if (state.isEvxml && state.secondEvXmlBeginTime && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
- // nodeDetail.time = nodeDetail.time + state.secondEvXmlBeginTime;
- // nodeDetail.endtime = nodeDetail.endtime + state.secondEvXmlBeginTime;
- // usetime = usetime + state.secondEvXmlBeginTime;
- // relativeTime = relativeTime + state.secondEvXmlBeginTime;
- // }
- if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
- 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 = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables || [];
- if ([121].includes(state.subjectId)) {
- tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
- }
- // console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
- // console.log('👀看看endtime', nodeDetail.duration, relaEndtime, fixtime, i)
- // console.log('音符时间',nodeDetail.i,nodeDetail.time,nodeDetail.endtime)
- tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
- const maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
- nodeDetail.noteLength = maxNum || 1;
- allNotes.push(nodeDetail);
- allNoteId.push(nodeDetail.id);
- measures.push(nodeDetail);
- /**
- * bug: #9877
- * 多分轨合并展示的曲子,不同分轨,同一小节音符的数量可能不能,不能只通过tickables的长度判断该小节的音符数量
- */
- if (si < maxNum - 1) {
- si++;
- } else {
- si = 0;
- relaMeasureLength = 0;
- measures = [];
- }
- preNoteEndTime = nodeDetail.endtime;
- }
- i++;
- }
- // 按照时间轴排序
- const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => Object.assign(item,{i:index}));
- // const sortArray = allNotes.sort((a, b) => a.time - b.time).map((item, index) => ({ ...item, i: index }));
- // const sortArray = allNotes.map((item, index) => ({ ...item, i: index }));
- console.timeEnd("音符跑完时间");
- try {
- osmd.cursor.reset();
- } catch (error) {}
- state.activeMeasureIndex = sortArray[0].MeasureNumberXML;
- 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;
- };
- // 解析xml,获取作词、作曲家名称
- 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() || '';
- }
- }
- }
- // 通过xml信息获取重播的小节信息
- 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') // 第多少小节,从1开始
- notesNumber = notesNumber ? Number(notesNumber) : 0
- if (direction === 'forward') {
- start = notesNumber
- } else if (direction === 'backward') {
- end = notesNumber
- repeatInfo.push({
- start,
- end
- })
- }
- }
- state.repeatInfo = repeatInfo
- // console.log('重播',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
- }
- }
- }
- // 处理妙极客xml谱面
- 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;
- if (notes && notes.length) {
- for (const note of notes) {
- if (maxLyricNum < note.getElementsByTagName("lyric").length) {
- maxLyricNum = note.getElementsByTagName("lyric").length
- }
- }
- }
- state.maxLyricNum = maxLyricNum;
- // state.osmd.EngravingRules.DYCustomRepeatCount = maxLyricNum;
- ;(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') {
- // creator.textContent = '测试一下1';
- }
-
- }
- }
- // 妙极客xml的倚音(grace)标签需要加上slash=yes属性
- if (graces && graces.length) {
- for (const grace of graces) {
- grace?.setAttribute('slash','yes');
- // console.log(grace,'倚音')
- }
- }
- // 妙极客xml部分小节没有音符,只有Segno,该小节不需要渲染,表示的是反复标记
- 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);
- }
- }
- /**
- * bug: #10289,曲目:1782672015612725196、1788040971888537602
- * 妙极客xml,多遍歌词循环的曲目,如果没有repeat标签,需要加上repeat标签
- * */
- if (maxLyricNum > 1) {
- const hasRepeat = xmlParse.querySelectorAll('repeat').length > 0
- if (!hasRepeat) {
- const lastMeasure = measures.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>`
- }
- // console.log(lastMeasure)
- }
- }
- }
- // 计算evxml的起始播放时间
- const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
- // xml拍号数
- 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")) : [];
- // 第一个音符的起始时间
- 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 = xmlParse.getElementsByTagName("timegap").length > 0;
- const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
- if (timeGaps && timeGaps.length && !firstNoteBeginTime) {
- 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)
- }
- // if (!hasTimeGap && !hasTimes) {
- // state.noTimes.push(xmlUrl)
- // }
-
- }
- /**
- * 兼容处理xml声部移调
- * 打谱软件可能会自动处理移调,这类型的xml就不用通过程序移调了
- * 没有通过软件处理的移调xml,才需要通过程序处理
- * 判读规则:只处理独奏的,不处理合奏的,
- * <instrument-name></instrument-name>标签的值为:Tenor Recorder(竖笛)、Panpipes(排箫)、Ocarina(陶笛)、Woodwind(葫芦丝)、空的和solo,需要程序处理移调
- */
- 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')) || [];
- // @ts-ignore
- const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
- // console.log('instrument名称',instrumentName)
- // 是否需要程序处理移调
- 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 = xmlNeedAdjustVoice
- }
- }
|