formateMusic.ts 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. import dayjs from "dayjs";
  2. import duration from "dayjs/plugin/duration";
  3. import state, { customData } from "/src/state";
  4. import { browser } from "../utils/index";
  5. import { transferJianNote } from "/src/helpers/customMusicScore"
  6. import {
  7. isSpecialMark,
  8. isSpeedKeyword,
  9. Fraction,
  10. SourceMeasure,
  11. isGradientWords,
  12. GRADIENT_SPEED_RESET_TAG,
  13. StringUtil,
  14. OpenSheetMusicDisplay,
  15. } from "/osmd-extended/src";
  16. import { GradualChange, speedInfo } from "./calcSpeed";
  17. import { beatUnitTo, speedBeatTo } from "/src/helpers/beatConfig"
  18. import { xmlDocRef } from "/src/view/music-score"
  19. const browserInfo = browser();
  20. dayjs.extend(duration);
  21. /**
  22. * 需要隐藏的中文速度文本
  23. */
  24. const hideSpeedWords: string[] = ["中速"];
  25. /**
  26. * 获取节拍器的时间
  27. * @param speed 速度
  28. * @param firstMeasure 曲谱第一个小节
  29. * @returns 节拍器的时间
  30. */
  31. export const getFixTime = (speed: number) => {
  32. const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
  33. let numerator = duration.numerator || 0;
  34. let denominator = duration.denominator || 4;
  35. const beatUnit = "quarter";
  36. // if (state.repeatedBeats) {
  37. // // 音频制作问题仅2拍不重复
  38. // numerator = numerator === 2 ? 4 : numerator;
  39. // } else if (numerator === 2 && denominator === 4) {
  40. // numerator = 4
  41. // }
  42. // 重复节拍,拍数*2进行计算
  43. if (state.repeatedBeats) {
  44. numerator = numerator*2;
  45. }
  46. // console.log('diff', speed, duration, formatBeatUnit(beatUnit), denominator, numerator, (numerator / denominator))
  47. return (60 / speed) * formatBeatUnit(beatUnit) * (numerator / denominator);
  48. };
  49. export const retain = (time: number) => {
  50. return Math.ceil(time * 1000000) / 1000000;
  51. };
  52. export const formatLyricsEntries = (note: any) => {
  53. const voiceEntries = note.parentStaffEntry?.voiceEntries || [];
  54. const lyricsEntries: string[] = [];
  55. for (const voic of voiceEntries) {
  56. if (voic.lyricsEntries?.table) {
  57. const values: any[] = Object.values(voic.lyricsEntries.table);
  58. for (const lyric of values) {
  59. lyricsEntries.push(lyric?.value.text);
  60. }
  61. }
  62. }
  63. return lyricsEntries;
  64. };
  65. export const getMeasureDurationDiff = (measure: any) => {
  66. const { realValue: SRealValue } = measure.activeTimeSignature;
  67. const { realValue: RRealValue } = measure.duration;
  68. return SRealValue - RRealValue;
  69. };
  70. /** 按照dorico的渐快渐慢生成对应的速度 */
  71. export const createSpeedInfo = (gradualChange: GradualChange | undefined, speed: number) => {
  72. if (gradualChange && speedInfo[gradualChange.startWord?.toLocaleLowerCase()]) {
  73. const notenum = Math.max(gradualChange.endXmlNoteIndex, 3);
  74. const speeds: number[] = [];
  75. const startSpeed = speed;
  76. const endSpeed = speed / speedInfo[gradualChange.startWord?.toLocaleLowerCase()];
  77. for (let index = 0; index < notenum; index++) {
  78. const speed = startSpeed + ((endSpeed - startSpeed) / notenum) * (index + 1);
  79. speeds.push(speed);
  80. }
  81. return speeds;
  82. }
  83. return;
  84. };
  85. const tranTime = (str: string = "") => {
  86. let result = str;
  87. const splits = str.split(":");
  88. if (splits.length === 1) {
  89. result = `00:${splits[0]}:00`;
  90. } else if (splits.length === 2) {
  91. result = `00:${splits[0]}:${splits[1]}`;
  92. }
  93. // console.log(`1970-01-01 00:${result}0`)
  94. return `1970-01-01 00:${result}0`;
  95. };
  96. export const getSlursNote = (note: any, pos?: "start" | "end") => {
  97. return pos === "end" ? note.noteElement.slurs[0]?.endNote : note.noteElement.slurs[0]?.startNote;
  98. };
  99. export const getNoteBySlursStart = (note: any, anyNoteHasSlurs?: boolean, pos?: "start" | "end") => {
  100. let activeNote = note;
  101. let slursNote = getSlursNote(activeNote, pos);
  102. for (const item of activeNote.measures) {
  103. if (item.noteElement.slurs.length) {
  104. slursNote = getSlursNote(item, pos);
  105. activeNote = item;
  106. }
  107. }
  108. return activeNote;
  109. };
  110. /** 根据 noteElement 获取note */
  111. export const getParentNote = (note: any) => {
  112. let parentNote;
  113. if (note) {
  114. // time = activeNote.time
  115. for (const n of state.times) {
  116. if (note === n.noteElement) {
  117. // console.log(note)
  118. return n;
  119. }
  120. }
  121. }
  122. return parentNote;
  123. };
  124. export type FractionDefault = {
  125. numerator: number;
  126. denominator: number;
  127. wholeValue: number;
  128. };
  129. export type Duration = FractionDefault & {
  130. TempoInBPM: number;
  131. beatUnit: string;
  132. };
  133. export const getDuration = (osmd?: OpenSheetMusicDisplay): Duration => {
  134. if (osmd) {
  135. const { Duration, TempoInBPM, ActiveTimeSignature, TempoExpressions } = osmd.GraphicSheet.MeasureList[0][0]?.parentSourceMeasure;
  136. if (Duration) {
  137. let beatUnit = "quarter";
  138. // for (const item of TempoExpressions) {
  139. // beatUnit = item.InstantaneousTempo.beatUnit || "quarter";
  140. // }
  141. const duration = formatDuration(ActiveTimeSignature, Duration) as unknown as FractionDefault;
  142. return {
  143. ...duration,
  144. TempoInBPM,
  145. beatUnit,
  146. };
  147. }
  148. }
  149. const duration = new Fraction() as unknown as FractionDefault;
  150. return {
  151. ...duration,
  152. TempoInBPM: 90,
  153. beatUnit: "quarter",
  154. };
  155. };
  156. export function formatDuration(activeTimeSignature: Fraction, duration: Fraction): Fraction {
  157. // 弱起第一小节duration不对
  158. return activeTimeSignature;
  159. }
  160. export function formatBeatUnit(beatUnit: string) {
  161. let multiple = 4;
  162. switch (beatUnit) {
  163. case "1024th":
  164. // bpm = bpm;
  165. multiple = 1024;
  166. break;
  167. case "512th":
  168. // divisionsFromNote = (noteDuration / 4) * 512;
  169. multiple = 512;
  170. break;
  171. case "256th":
  172. // divisionsFromNote = (noteDuration / 4) * 256;
  173. multiple = 256;
  174. break;
  175. case "128th":
  176. // divisionsFromNote = (noteDuration / 4) * 128;
  177. multiple = 128;
  178. break;
  179. case "64th":
  180. // divisionsFromNote = (noteDuration / 4) * 64;
  181. multiple = 64;
  182. break;
  183. case "32nd":
  184. // divisionsFromNote = (noteDuration / 4) * 32;
  185. multiple = 32;
  186. break;
  187. case "16th":
  188. // divisionsFromNote = (noteDuration / 4) * 16;
  189. multiple = 16;
  190. break;
  191. case "eighth":
  192. // divisionsFromNote = (noteDuration / 4) * 8;
  193. multiple = 8;
  194. break;
  195. case "quarter":
  196. multiple = 4;
  197. break;
  198. case "half":
  199. // divisionsFromNote = (noteDuration / 4) * 2;
  200. multiple = 2;
  201. break;
  202. case "whole":
  203. // divisionsFromNote = (noteDuration / 4);
  204. multiple = 1;
  205. break;
  206. case "breve":
  207. // divisionsFromNote = (noteDuration / 4) / 2;
  208. multiple = 0.5;
  209. break;
  210. case "long":
  211. // divisionsFromNote = (noteDuration / 4) / 4;
  212. multiple = 0.25;
  213. break;
  214. case "maxima":
  215. // divisionsFromNote = (noteDuration / 4) / 8;
  216. multiple = 0.125;
  217. break;
  218. default:
  219. break;
  220. }
  221. return multiple;
  222. }
  223. export type CustomInfo = {
  224. showSpeed: boolean;
  225. parsedXML: string;
  226. };
  227. /** 从xml中获取自定义信息,并删除多余的字符串 */
  228. export const getCustomInfo = (xml: string, resourceType?: string): CustomInfo => {
  229. const data = {
  230. showSpeed: true,
  231. parsedXML: xml,
  232. };
  233. //console.time('解析xml 耗时3')
  234. // const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  235. const xmlParse = xmlDocRef.value && resourceType === 'init' ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
  236. //console.timeEnd('解析xml 耗时3')
  237. const words: any = xmlParse?.getElementsByTagName("words");
  238. for (const word of words) {
  239. if (word && word.textContent?.trim() === "隐藏速度") {
  240. data.showSpeed = false;
  241. word.textContent = "";
  242. }
  243. if (word && word.textContent?.trim() === "@") {
  244. word.textContent = "segno";
  245. }
  246. }
  247. data.parsedXML = new XMLSerializer().serializeToString(xmlParse);
  248. return data;
  249. };
  250. /**
  251. * 替换文本标签中的内容
  252. */
  253. const replaceTextConent = (beforeText: string, afterText: string, ele: Element): Element => {
  254. const words: any = ele?.getElementsByTagName("words");
  255. for (const word of words) {
  256. if (word && word.textContent?.trim() === beforeText) {
  257. word.textContent = afterText;
  258. }
  259. }
  260. return ele;
  261. };
  262. /**
  263. * 添加第一分谱信息至当前分谱
  264. * @param ele 需要插入的元素
  265. * @param fitstParent 合奏谱第一个分谱
  266. * @param parent 需要添加的分谱
  267. */
  268. const setElementNoteBefore = (ele: Element, fitstParent: Element, parent?: Element | null) => {
  269. let noteIndex: number = 0;
  270. if (!fitstParent) {
  271. return;
  272. }
  273. for (let index = 0; index < fitstParent.childNodes.length; index++) {
  274. const element = fitstParent.childNodes[index];
  275. if (element.nodeName === "note") {
  276. noteIndex++;
  277. }
  278. if (element === ele) {
  279. break;
  280. }
  281. }
  282. if (noteIndex === 0 && parent) {
  283. parent.insertBefore(ele, parent.childNodes[0]);
  284. return;
  285. }
  286. if (parent && parent.childNodes.length > 0) {
  287. let noteIndex2: number = 0;
  288. const notes = Array.from(parent.childNodes).filter((child) => child.nodeName === "note");
  289. const lastNote = notes[notes.length - 1];
  290. if (noteIndex >= notes.length && lastNote) {
  291. parent.insertBefore(ele, parent.childNodes[Array.from(parent.childNodes).indexOf(lastNote)]);
  292. return;
  293. }
  294. for (let index = 0; index < notes.length; index++) {
  295. const element = notes[index];
  296. if (element.nodeName === "note") {
  297. noteIndex2 = noteIndex2 + 1;
  298. if (noteIndex2 === noteIndex) {
  299. parent.insertBefore(ele, element);
  300. break;
  301. }
  302. }
  303. }
  304. }
  305. // console.log(noteIndex, parent)
  306. };
  307. /**
  308. * 检查传入文字是否为重复关键词
  309. * @param text 总谱xml
  310. * @returns 是否是重复关键词
  311. */
  312. export const isRepeatWord = (text: string): boolean => {
  313. if (text) {
  314. const innerText = text.toLocaleLowerCase();
  315. const dsRegEx: string = "d\\s?\\.s\\.";
  316. const dcRegEx: string = "d\\.\\s?c\\.";
  317. return (
  318. innerText === "@" ||
  319. StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al fine", true) ||
  320. StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al coda", true) ||
  321. StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al fine", true) ||
  322. StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al coda", true) ||
  323. StringUtil.StringContainsSeparatedWord(innerText, dcRegEx) ||
  324. StringUtil.StringContainsSeparatedWord(innerText, "da\\s?capo", true) ||
  325. StringUtil.StringContainsSeparatedWord(innerText, dsRegEx, true) ||
  326. StringUtil.StringContainsSeparatedWord(innerText, "dal\\s?segno", true) ||
  327. StringUtil.StringContainsSeparatedWord(innerText, "al\\s?coda", true) ||
  328. StringUtil.StringContainsSeparatedWord(innerText, "to\\s?coda", true) ||
  329. StringUtil.StringContainsSeparatedWord(innerText, "a (la )?coda", true) ||
  330. StringUtil.StringContainsSeparatedWord(innerText, "fine", true) ||
  331. StringUtil.StringContainsSeparatedWord(innerText, "coda", true) ||
  332. StringUtil.StringContainsSeparatedWord(innerText, "segno", true)
  333. );
  334. }
  335. return false;
  336. };
  337. export const onlyVisible = (xml: string, partIndex: number, resourceType?: string): string => {
  338. if (!xml) return "";
  339. // console.log('原始xml')
  340. const detailId = state.examSongId + "";
  341. //console.time('解析xml 耗时4')
  342. // const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  343. const xmlParse = xmlDocRef.value && !resourceType ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
  344. //console.timeEnd('解析xml 耗时4')
  345. const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
  346. const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");
  347. const parts: any = xmlParse.getElementsByTagName("part");
  348. // const firstTimeInfo = parts[0]?.getElementsByTagName('metronome')[0]?.parentElement?.parentElement?.cloneNode(true)
  349. const firstMeasures = [...parts[0]?.getElementsByTagName("measure")];
  350. const metronomes = [...parts[0]?.getElementsByTagName("metronome")];
  351. const words = [...parts[0]?.getElementsByTagName("words")];
  352. const codas = [...parts[0]?.getElementsByTagName("coda")];
  353. const rehearsals = [...parts[0]?.getElementsByTagName("rehearsal")];
  354. /** 第一分谱如果是约定的配置分谱则跳过 */
  355. if (partListNames[0]?.toLocaleUpperCase?.() === "COMMON") {
  356. partIndex++;
  357. partListNames.shift();
  358. }
  359. const visiblePartInfo = partList[partIndex];
  360. // console.log(visiblePartInfo, partIndex)
  361. // 根据后台已选择的分轨筛选出能切换的声轨
  362. //state.partListNames = partListNames;
  363. // console.log('分轨名称',state.partListNames)
  364. if (visiblePartInfo) {
  365. const id = visiblePartInfo.getAttribute("id");
  366. Array.from(parts).forEach((part: any) => {
  367. if (part && part.getAttribute("id") !== id) {
  368. part.parentNode?.removeChild(part);
  369. // 不等于第一行才添加避免重复添加
  370. } else if (part && part.getAttribute("id") !== "P1") {
  371. // 速度标记仅保留最后一个
  372. const metronomeData: {
  373. [key in string]: Element;
  374. } = {};
  375. for (let i = 0; i < metronomes.length; i++) {
  376. const metronome = metronomes[i];
  377. const metronomeContainer = metronome.parentElement?.parentElement?.parentElement;
  378. if (metronomeContainer) {
  379. const index = firstMeasures.indexOf(metronomeContainer);
  380. metronomeData[index] = metronome;
  381. }
  382. }
  383. Object.values(metronomeData).forEach((metronome) => {
  384. const metronomeContainer: any = metronome.parentElement?.parentElement;
  385. const parentMeasure: any = metronomeContainer?.parentElement;
  386. const measureMetronomes = [...(parentMeasure?.childNodes || [])];
  387. const metronomesIndex = metronomeContainer ? measureMetronomes.indexOf(metronomeContainer) : -1;
  388. // console.log(parentMeasure)
  389. if (parentMeasure && metronomesIndex > -1) {
  390. const index = firstMeasures.indexOf(parentMeasure);
  391. const activeMeasure = part.getElementsByTagName("measure")[index];
  392. setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
  393. }
  394. });
  395. /** word比较特殊需要精确到note位置 */
  396. words.forEach((word) => {
  397. let text = word.textContent || "";
  398. text = ["cresc."].includes(text) ? "" : text;
  399. if ((isSpecialMark(text) || isSpeedKeyword(text) || isGradientWords(text) || isRepeatWord(text) || GRADIENT_SPEED_RESET_TAG) && text) {
  400. const wordContainer = word.parentElement?.parentElement;
  401. const parentMeasure = wordContainer?.parentElement;
  402. const measureWords = [...(parentMeasure?.childNodes || [])];
  403. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  404. if (wordContainer && parentMeasure && wordIndex > -1) {
  405. const index = firstMeasures.indexOf(parentMeasure);
  406. const activeMeasure = part.getElementsByTagName("measure")[index];
  407. // 找当前小节是否包含word标签
  408. const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
  409. // 遍历word标签,检查是否和第一小节重复,如果有重复则不平移word
  410. const total = _words.reduce((total: any, _word: any) => {
  411. if (_word.textContent?.includes(text)) {
  412. total++;
  413. }
  414. return total;
  415. }, 0);
  416. if (total === 0) {
  417. if (["12280"].includes(detailId)) {
  418. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  419. } else {
  420. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  421. }
  422. }
  423. }
  424. }
  425. });
  426. /** word比较特殊需要精确到note位置 */
  427. codas.forEach((coda) => {
  428. const wordContainer = coda.parentElement?.parentElement;
  429. const parentMeasure = wordContainer?.parentElement;
  430. const measureWords = [...(parentMeasure?.childNodes || [])];
  431. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  432. if (wordContainer && parentMeasure && wordIndex > -1) {
  433. const index = firstMeasures.indexOf(parentMeasure);
  434. const activeMeasure = part.getElementsByTagName("measure")[index];
  435. if (["12280"].includes(detailId)) {
  436. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  437. } else {
  438. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  439. }
  440. }
  441. });
  442. rehearsals.forEach((rehearsal) => {
  443. const container = rehearsal.parentElement?.parentElement;
  444. const parentMeasure = container?.parentElement;
  445. // console.log(rehearsal)
  446. if (parentMeasure) {
  447. const index = firstMeasures.indexOf(parentMeasure);
  448. part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
  449. // console.log(index, parentMeasure, firstMeasures.indexOf(parentMeasure))
  450. }
  451. });
  452. } else {
  453. words.forEach((word, idx) => {
  454. const text = word.textContent || "";
  455. // if (idx == 0 && text) {
  456. // word.textContent = '测试一下'
  457. // word.setAttribute('default-y',60)
  458. // word.setAttribute('margin-left',300)
  459. // word.setAttribute('y',300)
  460. // 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>'
  461. // }
  462. if (isSpeedKeyword(text) && text) {
  463. const wordContainer = word.parentElement?.parentElement?.parentElement;
  464. if (wordContainer && wordContainer.firstElementChild && wordContainer.firstElementChild !== word) {
  465. const wordParent = word.parentElement?.parentElement;
  466. const fisrt = wordContainer.firstElementChild;
  467. wordContainer.insertBefore(wordParent, fisrt);
  468. }
  469. }
  470. });
  471. }
  472. // 最后一个小节的结束线元素不在最后 调整
  473. if (part && part.getAttribute("id") === id) {
  474. if (!resourceType) {
  475. const backups = Array.from(part.getElementsByTagName('backup')) || []
  476. for (let backup of backups) {
  477. // @ts-ignore
  478. if (backup && backup?.getElementsByTagName('duration')?.length) {
  479. state.isSingleMutliTrack = true;
  480. break;
  481. }
  482. }
  483. }
  484. const barlines = part.getElementsByTagName("barline");
  485. const lastParent = barlines[barlines.length - 1]?.parentElement;
  486. if (lastParent?.lastElementChild?.tagName !== "barline") {
  487. const children = lastParent?.children || [];
  488. for (let el of children) {
  489. if (el.tagName === "barline") {
  490. // 将结束线元素放到最后
  491. lastParent?.appendChild(el);
  492. break;
  493. }
  494. }
  495. }
  496. }
  497. });
  498. Array.from(partList).forEach((part) => {
  499. if (part && part.getAttribute("id") !== id) {
  500. part.parentNode?.removeChild(part);
  501. }
  502. });
  503. }
  504. // console.log(xmlParse)
  505. return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
  506. };
  507. export const onlyVisible2 = (xml: string, partIndexs: Array<any>, resourceType?: string): string => {
  508. if (!xml) return "";
  509. // console.log('原始xml')
  510. const detailId = state.examSongId + "";
  511. //console.time('解析xml 耗时4')
  512. // const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  513. const xmlParse = xmlDocRef.value ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
  514. //console.timeEnd('解析xml 耗时4')
  515. const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
  516. const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");
  517. const parts: any = xmlParse.getElementsByTagName("part");
  518. // const firstTimeInfo = parts[0]?.getElementsByTagName('metronome')[0]?.parentElement?.parentElement?.cloneNode(true)
  519. const hasMeasureIdx = Array.from(parts).findIndex((item: any) => item.getElementsByTagName("measure").length) || 0;
  520. const firstMeasures = [...parts[hasMeasureIdx]?.getElementsByTagName("measure")];
  521. const metronomes = [...parts[0]?.getElementsByTagName("metronome")];
  522. const words = [...parts[0]?.getElementsByTagName("words")];
  523. const codas = [...parts[0]?.getElementsByTagName("coda")];
  524. const rehearsals = [...parts[0]?.getElementsByTagName("rehearsal")];
  525. /** 第一分谱如果是约定的配置分谱则跳过 */
  526. if (partListNames[0]?.toLocaleUpperCase?.() === "COMMON") {
  527. partIndexs = partIndexs.map(item => item + 1)
  528. //partListNames.shift();
  529. }
  530. const visiblePartInfo = partList[partIndexs[0]];
  531. let ids: any = [];
  532. partIndexs.forEach(item => {
  533. if (partList[item]) {
  534. ids.push(partList[item]?.getAttribute("id"))
  535. }
  536. })
  537. // console.log(visiblePartInfo, partIndex)
  538. // 根据后台已选择的分轨筛选出能切换的声轨
  539. //state.partListNames = partListNames;
  540. // console.log('分轨名称',state.partListNames)
  541. if (visiblePartInfo && ids.length) {
  542. const id = visiblePartInfo.getAttribute("id");
  543. Array.from(parts).forEach((part: any) => {
  544. if (part && !ids.includes(part.getAttribute("id")) ) {
  545. part.parentNode?.removeChild(part);
  546. // 不等于第一行才添加避免重复添加
  547. } else if (part && part.getAttribute("id") !== "P1") {
  548. if (part && part.getAttribute("id") === id) {
  549. // 速度标记仅保留最后一个
  550. const metronomeData: {
  551. [key in string]: Element;
  552. } = {};
  553. for (let i = 0; i < metronomes.length; i++) {
  554. const metronome = metronomes[i];
  555. const metronomeContainer = metronome.parentElement?.parentElement?.parentElement;
  556. if (metronomeContainer) {
  557. const index = firstMeasures.indexOf(metronomeContainer);
  558. metronomeData[index] = metronome;
  559. }
  560. }
  561. Object.values(metronomeData).forEach((metronome) => {
  562. const metronomeContainer: any = metronome.parentElement?.parentElement;
  563. const parentMeasure: any = metronomeContainer?.parentElement;
  564. const measureMetronomes = [...(parentMeasure?.childNodes || [])];
  565. const metronomesIndex = metronomeContainer ? measureMetronomes.indexOf(metronomeContainer) : -1;
  566. // console.log(parentMeasure)
  567. if (parentMeasure && metronomesIndex > -1) {
  568. const index = firstMeasures.indexOf(parentMeasure);
  569. const activeMeasure = part.getElementsByTagName("measure")[index];
  570. setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
  571. }
  572. });
  573. /** word比较特殊需要精确到note位置 */
  574. words.forEach((word) => {
  575. let text = word.textContent || "";
  576. text = ["cresc."].includes(text) ? "" : text;
  577. if ((isSpecialMark(text) || isSpeedKeyword(text) || isGradientWords(text) || isRepeatWord(text) || GRADIENT_SPEED_RESET_TAG) && text) {
  578. const wordContainer = word.parentElement?.parentElement;
  579. const parentMeasure = wordContainer?.parentElement;
  580. const measureWords = [...(parentMeasure?.childNodes || [])];
  581. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  582. if (wordContainer && parentMeasure && wordIndex > -1) {
  583. const index = firstMeasures.indexOf(parentMeasure);
  584. const activeMeasure = part.getElementsByTagName("measure")[index];
  585. // 找当前小节是否包含word标签
  586. const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
  587. // 遍历word标签,检查是否和第一小节重复,如果有重复则不平移word
  588. const total = _words.reduce((total: any, _word: any) => {
  589. if (_word.textContent?.includes(text)) {
  590. total++;
  591. }
  592. return total;
  593. }, 0);
  594. if (total === 0) {
  595. if (["12280"].includes(detailId)) {
  596. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  597. } else {
  598. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  599. }
  600. }
  601. }
  602. }
  603. });
  604. /** word比较特殊需要精确到note位置 */
  605. codas.forEach((coda) => {
  606. const wordContainer = coda.parentElement?.parentElement;
  607. const parentMeasure = wordContainer?.parentElement;
  608. const measureWords = [...(parentMeasure?.childNodes || [])];
  609. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  610. if (wordContainer && parentMeasure && wordIndex > -1) {
  611. const index = firstMeasures.indexOf(parentMeasure);
  612. const activeMeasure = part.getElementsByTagName("measure")[index];
  613. if (["12280"].includes(detailId)) {
  614. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  615. } else {
  616. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  617. }
  618. }
  619. });
  620. rehearsals.forEach((rehearsal) => {
  621. const container = rehearsal.parentElement?.parentElement;
  622. const parentMeasure = container?.parentElement;
  623. // console.log(rehearsal)
  624. if (parentMeasure) {
  625. const index = firstMeasures.indexOf(parentMeasure);
  626. part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
  627. // console.log(index, parentMeasure, firstMeasures.indexOf(parentMeasure))
  628. }
  629. });
  630. }
  631. } else {
  632. if (part && part.getAttribute("id") === id) {
  633. words.forEach((word, idx) => {
  634. const text = word.textContent || "";
  635. // if (idx == 0 && text) {
  636. // word.textContent = '测试一下'
  637. // word.setAttribute('default-y',60)
  638. // word.setAttribute('margin-left',300)
  639. // word.setAttribute('y',300)
  640. // 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>'
  641. // }
  642. if (isSpeedKeyword(text) && text) {
  643. const wordContainer = word.parentElement?.parentElement?.parentElement;
  644. if (wordContainer && wordContainer.firstElementChild && wordContainer.firstElementChild !== word) {
  645. const wordParent = word.parentElement?.parentElement;
  646. const fisrt = wordContainer.firstElementChild;
  647. wordContainer.insertBefore(wordParent, fisrt);
  648. }
  649. }
  650. });
  651. }
  652. }
  653. // 最后一个小节的结束线元素不在最后 调整
  654. if (part && part.getAttribute("id") === id) {
  655. if (!resourceType) {
  656. const backups = Array.from(part.getElementsByTagName('backup')) || []
  657. for (let backup of backups) {
  658. // @ts-ignore
  659. if (backup && backup?.getElementsByTagName('duration')?.length) {
  660. state.isSingleMutliTrack = true;
  661. break;
  662. }
  663. }
  664. }
  665. const barlines = part.getElementsByTagName("barline");
  666. const lastParent = barlines[barlines.length - 1]?.parentElement;
  667. if (lastParent?.lastElementChild?.tagName !== "barline") {
  668. const children = lastParent?.children || [];
  669. for (let el of children) {
  670. if (el.tagName === "barline") {
  671. // 将结束线元素放到最后
  672. lastParent?.appendChild(el);
  673. break;
  674. }
  675. }
  676. }
  677. }
  678. });
  679. Array.from(partList).forEach((part) => {
  680. if (part && !ids.includes(part.getAttribute("id")) ) {
  681. part.parentNode?.removeChild(part);
  682. }
  683. });
  684. }
  685. // console.log(xmlParse)
  686. return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
  687. };
  688. // 倚音后连音线
  689. export const appoggianceFormate = (xmlParse: Document): Document => {
  690. if (!xmlParse) return xmlParse;
  691. const graces: any = xmlParse.querySelectorAll("grace");
  692. if (!graces.length) return xmlParse;
  693. const getNextElement = (el: HTMLElement): HTMLElement => {
  694. if (el.querySelector("grace")) {
  695. return getNextElement(el?.nextElementSibling as HTMLElement);
  696. }
  697. return el;
  698. };
  699. for (let grace of graces) {
  700. const notations = grace.parentElement?.querySelector("notations");
  701. if (notations && notations.querySelectorAll("slur").length > 1) {
  702. let nextEle: Element = getNextElement(grace.parentElement?.nextElementSibling as HTMLElement);
  703. if (nextEle && nextEle.querySelectorAll("slur").length > 0) {
  704. const slurNumber = Array.from(nextEle.querySelector("notations")?.children || []).map((el: Element) => {
  705. return el.getAttribute("number");
  706. });
  707. const slurs = notations.querySelectorAll("slur");
  708. for (let nota of slurs) {
  709. if (!slurNumber.includes(nota.getAttribute("number"))) {
  710. nextEle.querySelector("notations")?.appendChild(nota);
  711. }
  712. }
  713. }
  714. }
  715. }
  716. return xmlParse;
  717. };
  718. /** 根据ID获取最顶级ID */
  719. export const isWithinScope = (tree: any[], id: number): number => {
  720. if (!tree) return 0;
  721. let result = 0;
  722. for (const item of tree) {
  723. if (item.id === id) {
  724. result = item.id;
  725. break;
  726. }
  727. if (item.sysMusicScoreCategoriesList) {
  728. result = isWithinScope(item.sysMusicScoreCategoriesList, id);
  729. if (result > 0) {
  730. result = item.id;
  731. }
  732. if (result) break;
  733. }
  734. }
  735. return result;
  736. };
  737. class NoteList {
  738. notes: any[] = [];
  739. constructor(notes: any[]) {
  740. this.notes = notes;
  741. }
  742. public last() {
  743. return this.notes[this.notes.length - 1];
  744. }
  745. public list() {
  746. return this.notes;
  747. }
  748. }
  749. export const getNotesByid = (id: string): NoteList => {
  750. const notes = new NoteList(state.times.filter((item) => item.id === id));
  751. return notes;
  752. };
  753. /** 格式化当前曲谱缩放比例 */
  754. export const formatZoom = (num = 1) => {
  755. return num * state.zoom;
  756. };
  757. /** 妙极客多分轨的曲子,可能没有part-name标签,需要手动加上该标签 */
  758. export const xmlAddPartName = (xml: string) => {
  759. if (!xml) return "";
  760. console.time('解析xml 耗时')
  761. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  762. console.timeEnd('解析xml 耗时')
  763. const scoreParts = Array.from(xmlParse.getElementsByTagName("score-part"));
  764. for (const scorePart of scoreParts) {
  765. if (scorePart.getElementsByTagName("part-name").length === 0) {
  766. state.evxmlAddPartName = true;
  767. const name = scorePart.getAttribute("id") || "";
  768. const newPartName = `<part-name>${name}</part-name>`
  769. // scorePart.prepend(newPartName);
  770. scorePart.innerHTML = newPartName + scorePart.innerHTML;
  771. }
  772. if (scorePart.getElementsByTagName("part-name").length && !scorePart.getElementsByTagName("part-name")?.[0]?.textContent?.trim() ) {
  773. scorePart.getElementsByTagName("part-name")[0].textContent = scorePart.getAttribute("id") || "";
  774. }
  775. }
  776. xmlDocRef.value = xmlParse;
  777. return new XMLSerializer().serializeToString(xmlParse);
  778. }
  779. /** 格式化曲谱
  780. * 1.全休止符的小节,没有音符默认加个全休止符
  781. */
  782. export const formatXML = (xml: string, xmlUrl?: string, resourceType?: string): string => {
  783. if (!xml) return "";
  784. //console.time('解析xml 耗时7')
  785. // const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  786. const xmlParse = xmlDocRef.value && resourceType === 'init' ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
  787. //console.timeEnd('解析xml 耗时7')
  788. // 声调
  789. const fifths = xmlParse.getElementsByTagName("fifths");
  790. if (fifths && fifths.length) {
  791. // 是否是C调
  792. state.isCTone = fifths[0].textContent === '0'
  793. }
  794. const endings = Array.from(xmlParse.getElementsByTagName("ending"));
  795. for (const ending of endings) {
  796. // if (ending.getAttribute('type') === 'stop') {
  797. // // @ts-ignore
  798. // ending.parentNode?.removeChild(ending.parentNode?.getElementsByTagName('bar-style')[0])
  799. // }
  800. // @ts-ignore
  801. // ending.parentNode.parentNode?.removeChild(ending.parentNode)
  802. }
  803. const measures = Array.from(xmlParse.getElementsByTagName("measure"));
  804. state.firstMeasureNumber = measures[0] ? Number(measures[0].getAttribute('number') || 1) : 1;
  805. const minutes: any = xmlParse.getElementsByTagName("per-minute");
  806. let speeds: any = []
  807. for (const minute of minutes) {
  808. let measureSpeed = minute.textContent ? Number(minute.textContent) : 0;
  809. // 速度带附点,需要转换成不带附点的速度值
  810. // const hasSpeedDot = Array.from(minute?.parentElement?.children || []).some((item: any) => item?.tagName === 'beat-unit-dot')
  811. // measureSpeed = hasSpeedDot ? measureSpeed + measureSpeed/2 : measureSpeed;
  812. if (minute.textContent && measureSpeed) {
  813. speeds.push(Number(measureSpeed))
  814. }
  815. // if (hasSpeedDot && measureSpeed) {
  816. // minute.textContent = measureSpeed
  817. // const dotDom = minute?.parentElement.querySelector('beat-unit-dot')
  818. // minute?.parentElement?.removeChild(dotDom)
  819. // }
  820. }
  821. speeds = [...new Set(speeds)]
  822. const hasVaryingSpeed = speeds.length > 1 ? true : false
  823. // 如果后台没有设置速度,默认取xml速度,如果xml也没有速度,默认赋值100
  824. if (state.originSpeed === 0) {
  825. state.originSpeed = speeds[0] ? speeds[0] : 100;
  826. state.speed = state.originSpeed;
  827. }
  828. // 赋值谱面速度节拍器,没有的时候 以后台传入的为准
  829. const metronomeXml = xmlParse.getElementsByTagName('metronome')?.[0]
  830. const beatUnit = metronomeXml?.getElementsByTagName('beat-unit')?.[0]?.textContent || ''
  831. if(beatUnit){
  832. const beatUnitDot = metronomeXml?.getElementsByTagName('beat-unit-dot')?.[0]
  833. state.speedBeatUnit = beatUnitTo(beatUnit, !!beatUnitDot)
  834. }
  835. // 如果谱面和小节都没有打速度,osmd设置的小节速度默认取后台设置的速度
  836. if (speeds.length === 0) {
  837. ;(window as any).baseMeasureSpeed = state.originSpeed
  838. } else {
  839. // 当前谱面的速度转为4分音符速度 因为我们速度比例转为4分音符了
  840. state.originAudioPlayRate = speedBeatTo({unit:state.speedBeatUnit, speed:speeds[0]}, "1/4") / state.originSpeed
  841. }
  842. console.log('是否是变速的曲子:',hasVaryingSpeed,speeds)
  843. let repeats: any = [];
  844. if (state.partIndex === 999) {
  845. repeats = Array.from(xmlParse.querySelectorAll('repeat')) || [];
  846. } else {
  847. const hasCommon = xmlParse.querySelectorAll('part-name')?.[0]?.textContent === 'common';
  848. const currentTrackIndex = hasCommon ? state.partIndex + 1 : state.partIndex;
  849. repeats = Array.from(xmlParse.querySelectorAll('part')?.[currentTrackIndex]?.querySelectorAll('repeat')) || [];
  850. }
  851. compatibleXmlPitchVoice(xmlParse);
  852. // 获取作词、作曲家
  853. getComposer(xmlParse);
  854. // 处理重复小节信息
  855. parseXmlToRepeat(repeats)
  856. // 解析处理evxml
  857. if (state.isEvxml) {
  858. analyzeEvxml(xmlParse, xmlUrl);
  859. customizationXml(xmlParse);
  860. }
  861. // const words: any = xmlParse.getElementsByTagName("words");
  862. // for (const word of words) {
  863. // if (word && word.textContent?.trim() === "筒音作5") {
  864. // word.setAttribute('y',260)
  865. // 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>'
  866. // }
  867. // }
  868. // console.log(11111,Array.from(xmlParse.getElementsByTagName("staffline")),Array.from(xmlParse.getElementsByTagName("words")))
  869. let speed = -1
  870. let beats = -1;
  871. let beatType = -1;
  872. // 前面小节的拍子
  873. let preBeats: number = 4;
  874. let preBeatType: number = 4;
  875. let baseDivisions: number = 256;
  876. // 小节中如果没有节点默认为休止符
  877. for (const measure of measures) {
  878. if (beats === -1 && measure.getElementsByTagName("beats").length) {
  879. beats = parseInt(measure.getElementsByTagName("beats")[0].textContent || "4");
  880. }
  881. if (beatType === -1 && measure.getElementsByTagName("beat-type").length) {
  882. beatType = parseInt(measure.getElementsByTagName("beat-type")[0].textContent || "4");
  883. }
  884. if (speed === -1 && measure.getElementsByTagName('per-minute').length) {
  885. speed = Number(measure.getElementsByTagName('per-minute')[0]?.textContent)
  886. }
  887. // 当前小节的拍数
  888. const currentBeats = measure.getElementsByTagName("beats").length ? measure.getElementsByTagName("beats")[0]?.textContent : preBeats;
  889. const currentBeatType = measure.getElementsByTagName("beat-type").length ? measure.getElementsByTagName("beat-type")[0]?.textContent : preBeatType;
  890. preBeats = Number(currentBeats);
  891. preBeatType = Number(currentBeatType);
  892. const divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || String(baseDivisions));
  893. baseDivisions = divisions
  894. // 如果note节点里面有space节点,并且没有duration节点,代表这是一个空白节点,需要删除
  895. if (measure.getElementsByTagName("note").length && state.isEvxml) {
  896. const noteList = Array.from(measure.getElementsByTagName("note")) || [];
  897. noteList.forEach((note: any) => {
  898. // if (note.getElementsByTagName("space").length && !note.getElementsByTagName("duration").length) {
  899. // measure.removeChild(note);
  900. // }
  901. // 非倚音音符
  902. if (!note.getElementsByTagName("grace").length) {
  903. if (!note.getElementsByTagName("duration").length || (note.getElementsByTagName("duration").length && note.getElementsByTagName("duration")[0]?.textContent == 0)) {
  904. measure.removeChild(note);
  905. }
  906. }
  907. });
  908. }
  909. // 如果有特殊中文速度文本,需要删除
  910. const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  911. if (measure.getElementsByTagName("words").length && state.isEvxml) {
  912. const wordList = Array.from(measure.getElementsByTagName("words")) || [];
  913. wordList.forEach((word: any) => {
  914. // TODO:删除妙极客曲子无意义的words
  915. // wordArr?.push(word?.textContent)
  916. if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
  917. measure.removeChild(word.parentNode.parentNode);
  918. // deleteWordArr?.push(word?.textContent)
  919. }
  920. // if(hideSpeedWords.includes(word?.textContent) && word?.parentNode?.parentNode) {
  921. // measure.removeChild(word.parentNode.parentNode);
  922. // }
  923. })
  924. }
  925. if (measure.getElementsByTagName("note").length === 0) {
  926. const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
  927. if (forwardTimeElement) {
  928. forwardTimeElement.textContent = "0";
  929. }
  930. measure.innerHTML =
  931. measure.innerHTML +
  932. `
  933. <note>
  934. <rest measure="yes"/>
  935. <duration>${divisions * beats}</duration>
  936. <voice>1</voice>
  937. <type>whole</type>
  938. </note>`;
  939. } else if (state.musicRenderType !== 'staff') {
  940. transferJianNote(measure, divisions, preBeats, preBeatType)
  941. }
  942. }
  943. xmlDocRef.value = xmlParse;
  944. return new XMLSerializer().serializeToString(xmlParse);
  945. };
  946. /** 获取所有音符的时值,以及格式化音符 */
  947. export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
  948. const customNoteRealValue = customData.customNoteRealValue;
  949. const customNoteCurrentTime = customData.customNoteCurrentTime;
  950. const detailId = state.examSongId + "";
  951. const partIndex = state.partIndex + "";
  952. //let fixtime = browserInfo.huawei ? 0.08 : 0; //getFixTime()
  953. let fixtime = 0;
  954. const allNotes: any[] = [];
  955. const allNoteId: string[] = [];
  956. const allMeasures: any[] = [];
  957. const { originSpeed: baseSpeed } = state;
  958. let preMeasureNumber = 0;
  959. const formatRealKey = (realKey: number, detail: any) => {
  960. // 不是管乐迷, 不处理
  961. // if (state.appName !== "GYM") return realKey;
  962. // 长笛的LEVEL 2-5-1条练习是泛音练习,以每小节第一个音的指法为准,高音不变变指法。
  963. const olnyOneIds = ["906"];
  964. if (olnyOneIds.includes(state.cbsExamSongId)) {
  965. return detail.measures[0]?.realKey || realKey;
  966. }
  967. // 圆号的LEVEL 2-5条练习是泛音练习,最后四小节指法以连音线第一个小节为准
  968. const olnyOneIds2 = ["782", "784"];
  969. if (olnyOneIds2.includes(state.cbsExamSongId)) {
  970. const measureNumbers = [14, 16, 30, 32];
  971. if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
  972. return allNotes[allNotes.length - 1]?.realKey || realKey;
  973. }
  974. }
  975. // 2-6 第三小节指法按照第一个音符显示
  976. const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
  977. if (filterIds.includes(state.cbsExamSongId)) {
  978. if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
  979. return detail.measures[0]?.realKey || realKey;
  980. }
  981. }
  982. return realKey;
  983. };
  984. if (!osmd.cursor) return [];
  985. const iterator: any = osmd.cursor.Iterator;
  986. // console.log("🚀 ~ iterator:", iterator)
  987. console.time("音符跑完时间");
  988. let i = 0;
  989. let si = 0;
  990. let measures: any[] = [];
  991. let stepSpeeds: number[] = [];
  992. /** 弱起时间 */
  993. let difftime = 0;
  994. let usetime = 0;
  995. let relaMeasureLength = 0;
  996. let beatUnit = "quarter";
  997. let gradualSpeed;
  998. let gradualChange: GradualChange | undefined;
  999. let gradualChangeIndex = 0;
  1000. let totalMultipleRestMeasures = 0;
  1001. let multipleRestMeasures = 0;
  1002. let staveNoteIndex = 0;
  1003. let staveIndex = 0;
  1004. let xmlMp3BeatFixTime = 0 // xml上节拍器的时间
  1005. let preNoteEndTime = 0; // 上一个音符的结束时间
  1006. let preNoteMeasureNumber: any = null; // 上一个小节的number值
  1007. let currentRealTempo: any = {}; // 当前小节的速度与拍号信息
  1008. const _notes = [] as any[];
  1009. if (state.gradualTimes) {
  1010. console.log("后台设置的渐慢小节时间", state.gradual, state.gradualTimes);
  1011. }
  1012. let currentTimeStamp = iterator.currentTimeStamp.RealValue;
  1013. const currentTimes = [] as any[];
  1014. let isSetNextNoteReal = false;
  1015. let differFrom = 0;
  1016. // let testIdx = 0;
  1017. let repeatIdx = 0; // 循环的次数
  1018. /**
  1019. * 当多选声部的时候 ,取选择的第一个声部
  1020. * 总谱渲染时,需要取第一个渲染的声轨名字,canSelectTracks返回的声轨名字可能不是第一个,顺序有问题,需要用state.osmd.Sheet.Instruments
  1021. */
  1022. // const firstTrackName = state.combinePartIndexs.length>1 ? state.partListNames[state.combinePartIndexs[0]] : state.canSelectTracks[0] || "";
  1023. const filterInstruments = state.osmd.Sheet.Instruments.filter(item => item.Name?.toLocaleLowerCase() !== 'common' )
  1024. const firstTrackName = state.combinePartIndexs.length>1 ? state.partListNames[state.combinePartIndexs[0]] : (filterInstruments[0].Name || filterInstruments[0].NameLabel.text || "");
  1025. // const currentTrackIndex = state.isCombineRender && state.combinePartIndexs.length > 1 ? state.combinePartIndexs[0] : 0;
  1026. const currentTrackIndex = 0;
  1027. while (!iterator.EndReached) {
  1028. // console.log({ ...iterator });
  1029. /** 多声轨合并显示,当前音符的时值取所有声轨中的最小值 */
  1030. if (state.isCombineRender) {
  1031. iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
  1032. const trackName = state.isEvxml && state.evxmlAddPartName ? item.parentVoice.parent.IdString || '' : item.parentVoice.parent.Name || '';
  1033. return trackName?.trim() === firstTrackName
  1034. });
  1035. }
  1036. // 多轨合并显示,或者单轨多声部的情况,需要过滤掉下半边声部的音符
  1037. if ( ((!state.isCombineRender && state.isSingleMutliTrack) || state.isCombineRender) && iterator.currentVoiceEntries.length) {
  1038. iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
  1039. return item.ParentVoice.voiceId === 1
  1040. });
  1041. }
  1042. let minIndex = 0, elRealValue = 0
  1043. for (let index = 0; index < iterator.currentVoiceEntries.length; index++) {
  1044. const element = iterator.currentVoiceEntries[index];
  1045. if (element.isGrace) {
  1046. if (minIndex == index && minIndex == 0) {
  1047. minIndex = iterator.currentVoiceEntries.length > 1 ? 1 : 0
  1048. }
  1049. continue
  1050. }
  1051. if (element.notes[0].length.realValue < elRealValue) {
  1052. minIndex = index
  1053. }
  1054. // console.log(element.notes[0].SourceMeasure.MeasureNumberXML,element.notes[0].playbackInstrumentId,element.ParentVoice.voiceId)
  1055. elRealValue = element.notes[0].length.realValue
  1056. }
  1057. if (minIndex !== 0 && state.isCombineRender && iterator.currentVoiceEntries[minIndex]) {
  1058. iterator.currentVoiceEntries[minIndex].Notes[0].NoteToGraphicalNoteObjectId = iterator.currentVoiceEntries?.[0].Notes[0].NoteToGraphicalNoteObjectId;
  1059. }
  1060. const voiceEntries = iterator.currentVoiceEntries?.[minIndex] ? [iterator.currentVoiceEntries?.[minIndex]] : [];
  1061. let currentVoiceEntries: any[] = [];
  1062. // 多分轨,当前小节最大音符数量
  1063. let maxNoteNum = 0;
  1064. // iterator.currentMeasure?.verticalMeasureList?.forEach((item: any) => maxNoteNum = Math.max(maxNoteNum, item?.staffEntries?.length || 0))
  1065. maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
  1066. // console.log(iterator.currentMeasure.MeasureNumberXML,maxNoteNum,iterator.currentMeasure?.verticalSourceStaffEntryContainers.length)
  1067. // 单声部多声轨
  1068. if (state.multitrack > 0) {
  1069. currentVoiceEntries = [...iterator.CurrentVoiceEntries];
  1070. } else {
  1071. currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
  1072. return n && n?.ParentVoice?.VoiceId != 1;
  1073. });
  1074. }
  1075. let currentTime = 0;
  1076. let isDouble = false;
  1077. let isMutileSubject = false;
  1078. if (currentVoiceEntries.length && !isSetNextNoteReal) {
  1079. isDouble = true;
  1080. let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
  1081. notes.push(...n.Notes);
  1082. return notes;
  1083. }, [] as any);
  1084. // 过滤掉倚音和和弦音符
  1085. voiceNotes = voiceNotes.filter((note: any) => (!note.IsGraceNote && !note.IsChordNote) )
  1086. voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
  1087. currentTime = voiceNotes?.[0]?.length?.realValue || 0;
  1088. if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
  1089. const min = voiceNotes[0]?.length?.realValue || 0;
  1090. const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
  1091. differFrom = max - min;
  1092. isSetNextNoteReal = differFrom === 0 ? false : true;
  1093. }
  1094. }
  1095. // 多声部上下音符没对齐,光标多走一拍
  1096. if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
  1097. isMutileSubject = true;
  1098. }
  1099. if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
  1100. isDouble = true;
  1101. currentTime = differFrom;
  1102. isSetNextNoteReal = false;
  1103. differFrom = 0;
  1104. }
  1105. currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
  1106. currentTimeStamp = iterator.currentTimeStamp.realValue;
  1107. for (const v of voiceEntries) {
  1108. let note = v.notes[0];
  1109. if (note.IsGraceNote) {
  1110. // 如果是装饰音, 取不是装饰音的时值
  1111. const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace);
  1112. if (!voice) {
  1113. continue;
  1114. }
  1115. note = voice.notes[0];
  1116. }
  1117. note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
  1118. // 有倚音
  1119. if (note?.voiceEntry?.isGrace) {
  1120. isDouble = true;
  1121. let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
  1122. notes.push(...n.notes);
  1123. return notes;
  1124. }, []);
  1125. ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
  1126. currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
  1127. }
  1128. if (state.multitrack > 0 && currentTime > note.length.realValue) {
  1129. currentTime = note.length.realValue;
  1130. }
  1131. note.maxNoteNum = maxNoteNum;
  1132. note.trackIndex = minIndex;
  1133. currentRealTempo = iterator.currentMeasure.tempoExpressions.length ? iterator.currentMeasure.tempoExpressions.find((item: any) => item?.InstantaneousTempo?.isMetronomeMark)?.InstantaneousTempo || currentRealTempo : currentRealTempo;
  1134. const { beatUnit="quarter", dotted=false, tempoInBpm=state.originSpeed } = currentRealTempo
  1135. const speedBeatUnit = beatUnitTo(beatUnit, dotted)
  1136. _notes.push({
  1137. measureNum: note?.sourceMeasure?.MeasureNumberXML,
  1138. note,
  1139. iterator: { ...iterator },
  1140. currentTime,
  1141. isDouble,
  1142. isMutileSubject,
  1143. // measuresTempoInBPM: note?.sourceMeasure?.tempoInBPM,
  1144. // 转换成1/4拍的速度
  1145. measuresTempoInBPM: speedBeatTo({unit: speedBeatUnit || "1/4",speed: tempoInBpm || 0}, `1/4`),
  1146. speedBeatUnit, // 当前谱面小节的速度对应的是几分音符
  1147. currentRealTempo
  1148. });
  1149. }
  1150. iterator.moveToNextVisibleVoiceEntry(false);
  1151. // 从头开始循环,repeatIdx标记+1
  1152. if (iterator.backJumpOccurred) {
  1153. repeatIdx += 1;
  1154. }
  1155. iterator.repeatIdx = repeatIdx;
  1156. // console.log('小节',testIdx,iterator.repeatIdx,iterator.EndReached,iterator.currentMeasureIndex,iterator.backJumpOccurred,iterator.forwardJumpOccurred)
  1157. // testIdx += 1;
  1158. }
  1159. // 是否是变速的曲子
  1160. const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
  1161. console.log('变速曲子',hasVaryingSpeed, _notes)
  1162. let noteIds: any = [];
  1163. // let voicesBBox: any = null;
  1164. for (let { note, iterator, currentTime, isDouble, isMutileSubject, speedBeatUnit, measuresTempoInBPM } of _notes) {
  1165. if (note) {
  1166. if (preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  1167. si = 0
  1168. }
  1169. if (si === 0 && preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  1170. preMeasureNumber = note?.sourceMeasure?.MeasureNumberXML
  1171. allMeasures.push(note.sourceMeasure);
  1172. }
  1173. // if (si === 0 && state.isSpecialBookCategory) {
  1174. // for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
  1175. // if (expression?.InstantaneousTempo?.beatUnit) {
  1176. // // 取最后一个有效的tempo
  1177. // beatUnit = expression.InstantaneousTempo.beatUnit;
  1178. // }
  1179. // }
  1180. // }
  1181. // 判断是否是同一小节
  1182. if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
  1183. staveNoteIndex++
  1184. } else {
  1185. // staveIndex不同,重新赋值
  1186. staveIndex = note.sourceMeasure?.MeasureNumberXML
  1187. staveNoteIndex = 0
  1188. }
  1189. let measureSpeed = note.sourceMeasure.tempoInBPM;
  1190. const { metronomeNoteIndex } = iterator.currentMeasure;
  1191. if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
  1192. measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
  1193. }
  1194. // 当前的分轨
  1195. let activeVerticalMeasureList: any = [];
  1196. /**
  1197. * bug: #9959
  1198. * 多分轨合并展示,第一分轨又可能获取不到对应的音符,需要在当前小节中音符最多的分轨中去查找音符
  1199. */
  1200. // if (state.isCombineRender) {
  1201. // const allTrackList = note.sourceMeasure.verticalMeasureList;
  1202. // let maxIdx = 0, maxNote = 0;
  1203. // allTrackList.forEach((item: any, index: number) => {
  1204. // if (item?.vfVoices['1']?.tickables?.length > maxNote) {
  1205. // maxIdx = index
  1206. // maxNote = item?.vfVoices['1']?.tickables?.length
  1207. // }
  1208. // })
  1209. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[maxIdx]] || [];
  1210. // } else {
  1211. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
  1212. // }
  1213. // 合并展示某些分轨,需要把展示的分轨筛选出来
  1214. if (state.isCombineRender && note.sourceMeasure.verticalMeasureList.length) {
  1215. note.sourceMeasure.verticalMeasureList = note.sourceMeasure?.verticalMeasureList.filter((item: any) => state.canSelectTracks.includes(item?.parentStaff?.parentInstrument.Name?.trim()))
  1216. }
  1217. activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentTrackIndex]] || [];
  1218. // 某些情况下,合并显示的妙极客曲子,note.sourceMeasure?.verticalMeasureList可能为空数组
  1219. if (state.isCombineRender && state.isEvxml && note.sourceMeasure?.verticalMeasureList.length === 0) {
  1220. activeVerticalMeasureList = osmd.GraphicSheet.MeasureList.find((item: any) => item[0]?.MeasureNumber === note.sourceMeasure.MeasureNumberXML) || [];
  1221. }
  1222. let currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
  1223. /**
  1224. * TODO:多分轨合并的小节,音符可能没有id,此时就去其它分轨找
  1225. */
  1226. const vmLength = note.sourceMeasure?.verticalMeasureList?.length
  1227. let currentVmIndex = 0;
  1228. let hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1229. while (!hasSvgElement && vmLength > 1 && currentVmIndex <= vmLength - 1 && currenrtVfVoices !== null) {
  1230. currentVmIndex += 1;
  1231. activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentVmIndex]] || [];
  1232. currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
  1233. hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1234. }
  1235. const { realValue } = iterator.currentTimeStamp;
  1236. const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(
  1237. iterator.currentMeasure.activeTimeSignature,
  1238. iterator.currentMeasure.duration
  1239. );
  1240. let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
  1241. if (customNoteRealValue[i]) {
  1242. // console.log(NoteRealValue, customNoteRealValue[i])
  1243. NoteRealValue = customNoteRealValue[i];
  1244. }
  1245. if (isDouble && currentTime > 0) {
  1246. if (currentTime != NoteRealValue) {
  1247. // console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
  1248. NoteRealValue = currentTime;
  1249. }
  1250. }
  1251. // note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
  1252. // 管乐迷,按自定义按读取到的音符时值
  1253. if (customNoteCurrentTime) {
  1254. if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
  1255. // console.log(NoteRealValue, currentTimes[i + 1])
  1256. NoteRealValue = currentTimes[i + 1];
  1257. }
  1258. }
  1259. let relativeTime = usetime;
  1260. // 妙极客的曲子,修复有的音符有times,有的音符没有times导致的,累计时长错误问题
  1261. if (state.isEvxml && relativeTime < preNoteEndTime - fixtime) {
  1262. relativeTime = preNoteEndTime - fixtime
  1263. }
  1264. let beatSpeed = 0;
  1265. // 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度,否则mp3速度不对
  1266. // if (measureSpeed !== baseSpeed && !hasVaryingSpeed) {
  1267. // beatSpeed = baseSpeed || measureSpeed || 100
  1268. // } else {
  1269. // beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  1270. // }
  1271. // 计算音符时值,使用转换成1/4的速度计算
  1272. beatSpeed = measuresTempoInBPM;
  1273. // let beatSpeed = measureSpeed || baseSpeed
  1274. beatSpeed = beatSpeed / state.originAudioPlayRate;
  1275. // 如果有节拍器,需要将节拍器的时间算出来
  1276. if (i === 0) {
  1277. if(state.isOpenMetronome){
  1278. fixtime += getFixTime(beatSpeed);
  1279. state.fixtime = fixtime;
  1280. }
  1281. // 存储mp3节拍器时间
  1282. xmlMp3BeatFixTime = getFixTime(beatSpeed)
  1283. // console.log("fixtime:", fixtime, '速度:', beatSpeed, "state.isSpecialBookCategory:", state.isSpecialBookCategory, 'state.isOpenMetronome:', state.isOpenMetronome);
  1284. }
  1285. let gradualLength = 0;
  1286. // let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  1287. let speed = measureSpeed ? measureSpeed : baseSpeed;
  1288. gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
  1289. gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
  1290. if (!gradualSpeed || gradualSpeed.length < 2) {
  1291. gradualSpeed = createSpeedInfo(gradualChange, speed);
  1292. }
  1293. // console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
  1294. const measureListIndex = iterator.currentMeasure.measureListIndex;
  1295. // 计算相差时间按照比例分配到所有音符上
  1296. if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
  1297. const withInRangeNote = state.gradual.find((item, index) => {
  1298. const nextItem: any = state.gradual[index + 1];
  1299. return (
  1300. item[0].measureIndex <= measureListIndex &&
  1301. item[1]?.measureIndex! >= measureListIndex &&
  1302. (!nextItem || nextItem?.[0].measureIndex !== measureListIndex)
  1303. );
  1304. });
  1305. const [first, last] = withInRangeNote || [];
  1306. if (first && last) {
  1307. // 小节数量
  1308. const continuous = last.measureIndex - first.measureIndex;
  1309. // 开始小节内
  1310. const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
  1311. // 结束小节内
  1312. const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
  1313. // 范围内小节
  1314. const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
  1315. if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
  1316. const startTime = state.gradualTimes[first.measureIndex];
  1317. const endTime = state.gradualTimes[last.measureIndex];
  1318. if (startTime && endTime) {
  1319. const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
  1320. const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
  1321. gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. const _noteLength = NoteRealValue;
  1327. // 当前音符的持续时长,当前音符的RealValue值*拍数*(60/后台设置的基准速度)
  1328. let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1329. // 小节时长
  1330. const measureLength = vRealValue * 4 * (60 / beatSpeed);
  1331. // console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
  1332. // console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
  1333. /**
  1334. * TODO:摇篮曲-人音-排箫(1788501975122489346),第12小节音符持续时间特殊处理
  1335. */
  1336. if (['1788501975122489346','1788502467554750466'].includes(state.cbsExamSongId)) {
  1337. if (i == 13) {
  1338. noteLength = noteLength / 2;
  1339. }
  1340. if (i == 44) {
  1341. noteLength = noteLength * 6;
  1342. }
  1343. if (i == 56) {
  1344. noteLength = noteLength * 4;
  1345. }
  1346. }
  1347. usetime += noteLength;
  1348. relaMeasureLength += noteLength;
  1349. let relaEndtime = noteLength + relativeTime;
  1350. // console.log('relaEndtime',noteLength, relativeTime)
  1351. const fixedKey = note.fixedKey || 0;
  1352. // const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
  1353. //const svgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1354. // 过滤掉ghostnote
  1355. const filterTickables = currenrtVfVoices?.tickables?.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
  1356. const svgElement = filterTickables?.[staveNoteIndex];
  1357. // console.log('si',si,i)
  1358. // console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
  1359. if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
  1360. i++
  1361. continue;
  1362. }
  1363. // console.log(iterator.currentMeasure)
  1364. // 如果是弱起就补齐缺省的时长,midi音频不需要考虑弱起
  1365. if (i === 0 && !state.isAppPlay) {
  1366. let _firstMeasureRealValue = 0;
  1367. const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
  1368. //计算第一个小节里面的音符时值是否等于整个小节的时值
  1369. staffEntries.forEach((_a: any) => {
  1370. // 需要过滤掉倚音音符
  1371. const matchNote = _a?.sourceStaffEntry?.voiceEntries?.length > 1 ? _a?.sourceStaffEntry?.voiceEntries.find((item: any) => !item.isGrace) : _a?.sourceStaffEntry?.voiceEntries?.[0]
  1372. if (matchNote?.notes?.[0]?.length?.realValue) {
  1373. _firstMeasureRealValue += matchNote.notes[0].length.realValue;
  1374. }
  1375. });
  1376. if (_firstMeasureRealValue < vRealValue) {
  1377. // console.log(_firstMeasureRealValue, vRealValue)
  1378. // 如果是弱起,将整个小节的时值减去该小节所有音符相加的时值,就是缺省的时值
  1379. difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1380. }
  1381. /**
  1382. * 管乐迷,部分弱起的曲目,mp3制作不标准,没有按照补齐弱起后的时间进行制作,需要单独处理
  1383. * 2670
  1384. */
  1385. // if (["2670"].includes(state.cbsExamSongId)) {
  1386. // // fixtime -= _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1387. // } else {
  1388. // if (difftime > 0 && !state.isEvxml) {
  1389. // fixtime += difftime;
  1390. // state.fixtime = fixtime;
  1391. // }
  1392. // }
  1393. if (difftime > 0 && !state.isEvxml) {
  1394. fixtime += difftime;
  1395. state.fixtime = fixtime;
  1396. }
  1397. // 管乐迷 diff获取不准确时, 弱起补齐
  1398. if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
  1399. // difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1400. // fixtime += difftime;
  1401. }
  1402. // 如果是evxml,fixtime取读取xml的值
  1403. if (state.isEvxml) {
  1404. fixtime = state.evXmlBeginTime ? state.evXmlBeginTime : fixtime
  1405. state.fixtime = fixtime
  1406. }
  1407. console.log('节拍器时间',fixtime,state.evXmlBeginTime)
  1408. }
  1409. let stave = activeVerticalMeasureList[0]?.stave;
  1410. if (note.sourceMeasure.multipleRestMeasures) {
  1411. totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures;
  1412. multipleRestMeasures = 0;
  1413. }
  1414. if (multipleRestMeasures < totalMultipleRestMeasures) {
  1415. if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
  1416. multipleRestMeasures++;
  1417. } else {
  1418. multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
  1419. }
  1420. } else {
  1421. if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
  1422. multipleRestMeasures = 0;
  1423. totalMultipleRestMeasures = 0;
  1424. } else {
  1425. multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
  1426. }
  1427. }
  1428. // console.log(note.tie)
  1429. // console.log('👀看看endtime', duration, relaEndtime, fixtime, i)
  1430. // console.log('频率',note?.pitch?.frequency,i)
  1431. /**
  1432. * evxml的曲子,如果曲谱xml中带有times信息,则音符时值优先取times中的值
  1433. * 曲子:1795013295024062466(春暖花开),如果音符有times信息,休止符没有times信息,此种规则是认为休止符不参与时值计算的,需要过滤掉该休止符
  1434. */
  1435. let evNoteStartTime = 0, evNoteEndTime = 0;
  1436. if (state.isEvxml && note?.noteTimeInfo?.length === 0 && state.xmlHasTimes ) {
  1437. // 找出这个音符前面音符的结束时间
  1438. let preNoteTImes = allNotes[allNotes.length - 1]?.endtime*1000
  1439. if(!preNoteTImes){
  1440. //如果前一个音符没有结束时间,证明这个音符是第一个音符没有打时间,当有timegap以fixtime当开始时间(1795013294269087745),当第一个小节有times这个往前奏里面找补(1795013306436763649)
  1441. preNoteTImes = (state.evXmlBeginArr.length>0 ? fixtime : Math.max(fixtime - noteLength, 0))*1000
  1442. }
  1443. // 找出这个音符后面音符的开始时间
  1444. let nextI = i
  1445. let nextNoteTimes
  1446. // 多个连续的没有打时间的音符 需要平分时值
  1447. const notesRatio = []
  1448. while (!nextNoteTimes && nextI<_notes.length) {
  1449. notesRatio.push(_notes[nextI].note.length.realValue)
  1450. nextI++
  1451. if(_notes[nextI]?.note){ // 有可能_notes里面没有这个音符
  1452. nextNoteTimes = fliterNotesTime(_notes[nextI].note, preNoteTImes)
  1453. }
  1454. }
  1455. // 当最后音符就是没有打时间的音符,可能nextNoteTimes时间找不到时候取上个音符的结束时间加上这个音符的时间
  1456. if(!nextNoteTimes){
  1457. nextNoteTimes = preNoteTImes + noteLength*1000
  1458. }
  1459. // 判断有没有首位连续 首位连续的时候删掉这个音符
  1460. const allowRange = Math.abs(nextNoteTimes - preNoteTImes)< 10;
  1461. if (allowRange) {
  1462. note.maxNoteNum = note.maxNoteNum - 1;
  1463. // 唱名时间补齐,当删除这个音符的时候,上个音符的持续时间要加上这个音符的时间
  1464. allNotes[allNotes.length - 1].noteLengthTime += noteLength
  1465. i++
  1466. continue;
  1467. }else{
  1468. // 当多个连续的休止符没有打时间的时候 根据音符平均分配
  1469. if(notesRatio.length > 1){
  1470. const sum = notesRatio.reduce((acc:number, curr:number) => acc + curr, 0)
  1471. nextNoteTimes = (nextNoteTimes - preNoteTImes) * notesRatio[0] / sum + preNoteTImes
  1472. }
  1473. evNoteEndTime = nextNoteTimes/1000
  1474. evNoteStartTime = preNoteTImes/1000
  1475. // 当这个音符计算出来的时值大于本身这个音符的时值时候,取这个音符的长度,防止有前奏和间奏的时候,计算音符持续时长过长
  1476. if(evNoteEndTime - evNoteStartTime > noteLength){
  1477. evNoteEndTime = evNoteStartTime + noteLength
  1478. }
  1479. if (evNoteStartTime) {
  1480. relativeTime = evNoteStartTime - fixtime
  1481. }
  1482. }
  1483. }
  1484. if (state.isEvxml && note?.noteTimeInfo?.length ) {
  1485. let idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0;
  1486. // 如果是合并的小节的休止符
  1487. if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
  1488. const customRestId = `rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`;
  1489. idx = noteIds.filter((item: any) => item === customRestId)?.length || 0;
  1490. }
  1491. evNoteStartTime = note?.noteTimeInfo[idx]?.begin
  1492. evNoteEndTime = note?.noteTimeInfo[idx]?.end
  1493. if (evNoteStartTime) {
  1494. relativeTime = evNoteStartTime - fixtime
  1495. // usetime = evNoteStartTime - fixtime
  1496. }
  1497. // usetime = evNoteStartTime - fixtime
  1498. }
  1499. svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
  1500. // 如果是合并的休止小节,是没有渲染音符的,所以没有svgElement对象,也就没有id,此时需要添加自定义的一个id进度,便于多遍循环时,找到对应的noteTimeInfo里面的时间信息
  1501. if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
  1502. noteIds.push(`rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`)
  1503. }
  1504. // 如果该音符包含倚音,添加标记
  1505. let hasGraceNote = false;
  1506. if (svgElement?.modifiers?.length) {
  1507. hasGraceNote = svgElement?.modifiers.some((item: any) => item?.attrs?.type === "GraceNoteGroup")
  1508. }
  1509. const filterRepeatIdx = allNotes.filter((item: any) => item.noteId === note.NoteToGraphicalNoteObjectId).length
  1510. const nodeDetail = {
  1511. trackIndex: note.trackIndex, // 当前的音符属于第几条分轨
  1512. isStaccato: note.voiceEntry.isStaccato(),
  1513. isRestFlag: note.isRestFlag,
  1514. noteId: note.NoteToGraphicalNoteObjectId === undefined ? `restNote${note.sourceMeasure.MeasureNumberXML}` : note.NoteToGraphicalNoteObjectId,
  1515. // noteId: note.NoteToGraphicalNoteObjectId,
  1516. measureListIndex: note.sourceMeasure.measureListIndex,
  1517. MeasureNumberXML: note.sourceMeasure.MeasureNumberXML, // 当前的小节数,(从1开始)
  1518. _noteLength: _noteLength,
  1519. svgElement: svgElement,
  1520. frequency: note?.pitch?.frequency || -1,
  1521. nextFrequency: note?.pitch?.nextFrequency || -1,
  1522. prevFrequency: note?.pitch?.prevFrequency || -1,
  1523. difftime,
  1524. octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
  1525. speed,
  1526. beatSpeed,
  1527. i,
  1528. si,
  1529. stepSpeeds,
  1530. measureOpenIndex: allMeasures.length - 1,
  1531. measures,
  1532. tempoInBPM: note.sourceMeasure.tempoInBPM,
  1533. measureLength,
  1534. relaMeasureLength,
  1535. id: svgElement?.attrs.id,
  1536. hasGraceNote,
  1537. note: note.halfTone + 12, // see issue #224
  1538. fixtime, // 弱起补充的时间
  1539. relativeTime: retain(relativeTime),
  1540. time: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + fixtime), // 开始播放的时间
  1541. endtime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + fixtime), // 播放完成的时间
  1542. relaEndtime: retain(relaEndtime),
  1543. realValue,
  1544. halfTone: note.halfTone,
  1545. noteElement: note,
  1546. fixedKey,
  1547. realKey: 0,
  1548. duration: 0,
  1549. formatLyricsEntries: formatLyricsEntries(note),
  1550. stave,
  1551. firstVerticalMeasure: activeVerticalMeasureList[0],
  1552. noteLength: 1,
  1553. //osdmContext: osmd,
  1554. // speedbeatUnit: beatUnit,
  1555. speedBeatUnit, // 当前谱面小节的速度对应的是几分音符
  1556. multipleRestMeasures: multipleRestMeasures, // 当前合并小节的索引,从1开始到当前的totalMultipleRestMeasures结束,
  1557. totalMultipleRestMeasures, // 当前小节总的合并小节数
  1558. measureSpeed, // 小节速度
  1559. maxNoteNum: note.maxNoteNum, // 当前小节音符最多的分轨的音符数量
  1560. // repeatIdx: iterator.repeatIdx || 0, // 标记是第几遍循环,从0开始
  1561. repeatIdx: filterRepeatIdx,
  1562. noteLengthTime: noteLength, //当前音符时长
  1563. xmlNoteTime: 0, // xml上音符开始时间 唱名用
  1564. xmlNoteEndTime: 0, //xml上音符结束时间 唱名用
  1565. xmlMp3BeatFixTime, //xml上节拍器的时间
  1566. notBeatFixtime: state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime, // 不含节拍器的fixtime值 唱名用
  1567. notBeatTime: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)), // 不含节拍器的 音符开始时间
  1568. notBeatEndTime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)), // 不含节拍器的 音符结束时间
  1569. frequencyList: [note?.pitch?.frequency || -1], // 如果是和弦音符,需要添加多个音符的频率,用于评测
  1570. };
  1571. // console.log(i,'当前的小节',nodeDetail.MeasureNumberXML,totalMultipleRestMeasures,multipleRestMeasures)
  1572. // 如果是妙极客的曲子,并且第二遍循环播放需要等待时间,并且是第二遍循环的第一个小节的第一个音符
  1573. // if (state.isEvxml && state.secondEvXmlBeginTime && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
  1574. // nodeDetail.time = nodeDetail.time + state.secondEvXmlBeginTime;
  1575. // nodeDetail.endtime = nodeDetail.endtime + state.secondEvXmlBeginTime;
  1576. // usetime = usetime + state.secondEvXmlBeginTime;
  1577. // relativeTime = relativeTime + state.secondEvXmlBeginTime;
  1578. // }
  1579. // if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
  1580. // 如果是和弦音符,需要添加多个音符的频率,用于评测
  1581. if (note.voiceEntry.notes.length > 1) {
  1582. note.voiceEntry.notes.forEach((cnote: any) => {
  1583. if (cnote?.IsChordNote && cnote?.pitch?.frequency) {
  1584. nodeDetail.frequencyList.push(cnote.pitch.frequency)
  1585. }
  1586. })
  1587. }
  1588. const firstRepeatNodeId = allNotes.find((item: any) => item.MeasureNumberXML === state.timegapRepeatMeasureIndex)?.noteId || 0;
  1589. if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === state.timegapRepeatMeasureIndex && nodeDetail.noteId === firstRepeatNodeId) {
  1590. const currentWaitTime = state.evXmlBeginArr[nodeDetail.repeatIdx] || 0;
  1591. nodeDetail.time = nodeDetail.time + currentWaitTime;
  1592. nodeDetail.endtime = nodeDetail.endtime + currentWaitTime;
  1593. usetime = usetime + currentWaitTime;
  1594. relativeTime = relativeTime + currentWaitTime;
  1595. }
  1596. nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
  1597. nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
  1598. let tickables = currenrtVfVoices?.tickables || [];
  1599. if ([121].includes(state.subjectId)) {
  1600. tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
  1601. }
  1602. // console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
  1603. // console.log('👀看看endtime', nodeDetail.duration, relaEndtime, fixtime, i)
  1604. // console.log('音符时间',nodeDetail.i,nodeDetail.time,nodeDetail.endtime)
  1605. tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
  1606. let maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
  1607. // 妙极客的曲子,一个休止小节内可能有多个休止符,此时maxNum是0,需要针对这种情况作处理
  1608. if (note.isRestFlag && maxNum === 0) {
  1609. maxNum = note.maxNoteNum;
  1610. }
  1611. nodeDetail.noteLength = maxNum || 1;
  1612. allNotes.push(nodeDetail);
  1613. allNoteId.push(nodeDetail.id);
  1614. if ( measures.some((item: any) => item.MeasureNumberXML !== nodeDetail.MeasureNumberXML) ) {
  1615. measures = [];
  1616. measures.push(nodeDetail);
  1617. nodeDetail.measures = measures;
  1618. } else {
  1619. measures.push(nodeDetail);
  1620. }
  1621. /**
  1622. * bug: #9877
  1623. * 多分轨合并展示的曲子,不同分轨,同一小节音符的数量可能不能,不能只通过tickables的长度判断该小节的音符数量
  1624. */
  1625. if (si < maxNum - 1) {
  1626. si++;
  1627. } else {
  1628. si = 0;
  1629. relaMeasureLength = 0;
  1630. measures = [];
  1631. }
  1632. preNoteEndTime = nodeDetail.endtime;
  1633. }
  1634. preNoteMeasureNumber = note?.sourceMeasure?.MeasureNumberXML;
  1635. i++;
  1636. }
  1637. // 按照时间轴排序
  1638. const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => Object.assign(item,{i:index}));
  1639. // const sortArray = allNotes.sort((a, b) => a.time - b.time).map((item, index) => ({ ...item, i: index }));
  1640. // const sortArray = allNotes.map((item, index) => ({ ...item, i: index }));
  1641. // 给 xmlNoteTime 和 xmlNoteEndTime 赋值
  1642. let xmlNoteTime = 0
  1643. sortArray.map(item => {
  1644. const noteLengthTime = item.noteLengthTime
  1645. item.xmlNoteTime = retain(xmlNoteTime)
  1646. item.xmlNoteEndTime = retain(xmlNoteTime + noteLengthTime)
  1647. xmlNoteTime += noteLengthTime
  1648. })
  1649. console.timeEnd("音符跑完时间");
  1650. try {
  1651. osmd.cursor.reset();
  1652. } catch (error) {}
  1653. return sortArray;
  1654. };
  1655. /** 获取小节之间的连音线,仅同音高*/
  1656. export const getNoteByMeasuresSlursStart = (note: any) => {
  1657. let activeNote = note;
  1658. let tieNote;
  1659. if (note.noteElement.tie && note.noteElement.tie.StartNote) {
  1660. tieNote = note.noteElement.tie.StartNote;
  1661. }
  1662. if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
  1663. const arr: any = []
  1664. for (const note of state.times) {
  1665. if (tieNote === note.noteElement) {
  1666. arr.push(note)
  1667. }
  1668. }
  1669. if (arr.length) {
  1670. return arr.find((n: any) => n.i === (note.i - 1)) || arr[0]
  1671. }
  1672. }
  1673. return activeNote;
  1674. };
  1675. // 解析xml,获取作词、作曲家名称
  1676. const getComposer = (xmlParse: any) => {
  1677. const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
  1678. for (const creator of creators) {
  1679. if (creator && creator.getAttribute('type') === 'composer' && !state.musicComposer) {
  1680. state.musicComposer = creator.textContent?.trim() || '';
  1681. }
  1682. if (creator && creator.getAttribute('type') === 'lyricist' && !state.musicLyricist) {
  1683. state.musicLyricist = creator.textContent?.trim() || '';
  1684. }
  1685. }
  1686. }
  1687. // 通过xml信息获取重播的小节信息
  1688. const parseXmlToRepeat = (repeats: any) => {
  1689. if (!repeats.length) return
  1690. let repeatInfo: any = []
  1691. // 重复开始小节,结束小节
  1692. let start = 0, end = 0
  1693. for (let i = 0; i < repeats.length; i++) {
  1694. const element = repeats[i];
  1695. const direction = element.getAttribute('direction')
  1696. let parentElement = element.parentNode
  1697. while (parentElement && parentElement.tagName !== 'measure') {
  1698. parentElement = parentElement.parentNode
  1699. }
  1700. let notesNumber = parentElement.getAttribute('number') // 第多少小节,从1开始
  1701. notesNumber = notesNumber ? Number(notesNumber) : 0
  1702. if (direction === 'forward') {
  1703. start = notesNumber
  1704. } else if (direction === 'backward') {
  1705. end = notesNumber
  1706. repeatInfo.push({
  1707. start,
  1708. end
  1709. })
  1710. }
  1711. }
  1712. state.repeatInfo = repeatInfo
  1713. // console.log('重播',repeatInfo)
  1714. }
  1715. // 校验当前选段是否满足重播条件
  1716. export const verifyCanRepeat = (startNum: number, endNum: number) => {
  1717. let repeatIdx = -1
  1718. if (state.repeatInfo.length) {
  1719. for (let i = state.repeatInfo.length - 1; i >= 0; i--) {
  1720. const { start, end } = state.repeatInfo[i];
  1721. if (startNum <= start && endNum >= end) {
  1722. repeatIdx = i
  1723. return {
  1724. repeatIdx,
  1725. canRepeat: true
  1726. }
  1727. break;
  1728. }
  1729. }
  1730. return {
  1731. repeatIdx,
  1732. canRepeat: false
  1733. }
  1734. } else {
  1735. return {
  1736. repeatIdx,
  1737. canRepeat: false
  1738. }
  1739. }
  1740. }
  1741. // 处理妙极客xml谱面
  1742. const customizationXml = (xmlParse: any) => {
  1743. const credits: any = Array.from(xmlParse.querySelectorAll('credit'));
  1744. const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
  1745. const graces: any = Array.from(xmlParse.querySelectorAll('grace'));
  1746. const measures: any[] = Array.from(xmlParse.getElementsByTagName("measure"));
  1747. const notes: any[] = Array.from(xmlParse.getElementsByTagName("note"));
  1748. // 获取音符最多的歌词数,time最多的次数,取两者的最大值,用于自定义循环播放次数
  1749. let maxLyricNum = 0, maxTimeNum = 0;
  1750. if (notes && notes.length) {
  1751. for (const note of notes) {
  1752. if (maxLyricNum < note.getElementsByTagName("lyric").length) {
  1753. maxLyricNum = note.getElementsByTagName("lyric").length
  1754. }
  1755. if (maxTimeNum < note.getElementsByTagName("time").length) {
  1756. maxTimeNum = note.getElementsByTagName("time").length
  1757. }
  1758. }
  1759. }
  1760. state.maxLyricNum = Math.max(maxLyricNum, maxTimeNum);
  1761. // state.osmd.EngravingRules.DYCustomRepeatCount = maxLyricNum;
  1762. ;(window as any).DYCustomRepeatCount = state.maxLyricNum;
  1763. console.log('歌词次数',maxLyricNum)
  1764. if (credits && credits.length) {
  1765. for (const credit of credits) {
  1766. if (credit.getElementsByTagName("credit-type")?.[0]?.textContent === 'lyricist') {
  1767. const creditWord = credit.getElementsByTagName("credit-words")
  1768. creditWord?.[0].setAttribute('justify', 'right')
  1769. }
  1770. }
  1771. }
  1772. if (creators && creators.length) {
  1773. for (const creator of creators) {
  1774. if (creator.getAttribute('type') === 'lyricist') {
  1775. // creator.textContent = '测试一下1';
  1776. }
  1777. }
  1778. }
  1779. // 妙极客xml的倚音(grace)标签需要加上slash=yes属性
  1780. if (graces && graces.length) {
  1781. for (const grace of graces) {
  1782. grace?.setAttribute('slash','yes');
  1783. // console.log(grace,'倚音')
  1784. }
  1785. }
  1786. // 妙极客xml部分小节没有音符,只有Segno,该小节不需要渲染,表示的是反复标记
  1787. for (const measure of measures) {
  1788. const hasNote = measure.getElementsByTagName("note").length;
  1789. const hasSegno = measure.getElementsByTagName("segno").length;
  1790. const sounds = Array.from(measure.getElementsByTagName("sound"));
  1791. const hasSoundSegno = sounds.some((item: any) => item.getAttribute('segno') === 'segno' );
  1792. if (!hasNote && hasSegno && hasSoundSegno) {
  1793. const parent = measure.parentNode;
  1794. parent.removeChild(measure);
  1795. }
  1796. }
  1797. /**
  1798. * bug: #10289,曲目:1782672015612725196、1788040971888537602
  1799. * 妙极客xml,多遍歌词循环的曲目,如果没有repeat标签,需要加上repeat标签
  1800. * */
  1801. if (maxLyricNum > 1) {
  1802. const hasRepeat = xmlParse.querySelectorAll('repeat').length > 0;
  1803. if (!hasRepeat) {
  1804. const parts = xmlParse.querySelectorAll('score-partwise>part')
  1805. if (parts.length) {
  1806. for (const part of parts) {
  1807. const currentMeasures = part.querySelectorAll('measure').length ? Array.from(part.querySelectorAll('measure')) : [];
  1808. const lastMeasure: any = currentMeasures.last();
  1809. if (lastMeasure?.getElementsByTagName('barline').length) {
  1810. const barlineDom = lastMeasure?.getElementsByTagName('barline')[0]
  1811. barlineDom.innerHTML = barlineDom.innerHTML + `<repeat direction="backward" />`;
  1812. } else {
  1813. lastMeasure.innerHTML = lastMeasure.innerHTML + `
  1814. <barline location="right">
  1815. <bar-style>light-heavy</bar-style>
  1816. <repeat direction="backward" />
  1817. </barline>`
  1818. }
  1819. // console.log(lastMeasure)
  1820. }
  1821. }
  1822. }
  1823. }
  1824. }
  1825. // 计算evxml的起始播放时间
  1826. const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
  1827. // xml拍号数
  1828. const xmlNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('num');
  1829. const denNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('den');
  1830. const xmlNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('num');
  1831. const denNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('den');
  1832. const timeGaps: any = xmlParse.getElementsByTagName("timegap")?.length ? Array.from(xmlParse.getElementsByTagName("timegap")?.[0]?.getElementsByTagName("values")?.[0]?.getElementsByTagName("item")) : [];
  1833. state.xmlHasTimes = !!xmlParse.getElementsByTagName("times")?.length
  1834. // 第一个音符的起始时间
  1835. const firstMeasure = xmlParse.getElementsByTagName("measure")[0];
  1836. if (firstMeasure) {
  1837. const firstNoteBeginTime = firstMeasure.getElementsByTagName("times")[0]?.getElementsByTagName("time")[0]?.getAttribute('begin');
  1838. state.evXmlBeginTime = firstNoteBeginTime ? firstNoteBeginTime / 1000 : xmlNum ? 60 / state.originSpeed * xmlNum * 4/denNum : 0;
  1839. state.secondEvXmlBeginTime = firstNoteBeginTime ? 0 : xmlNum2 ? 60 / state.originSpeed * xmlNum2 * 4/denNum2 : 0;
  1840. const hasTimeGap = state.xmlHasTimeGap = xmlParse.getElementsByTagName("timegap").length > 0;
  1841. const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
  1842. if (timeGaps && timeGaps.length && !firstNoteBeginTime) {
  1843. // 有timegap的曲子,需要找到是从哪一小节开始循环的,默认是从第一节开始循环
  1844. const startRepeat = Array.from(xmlParse.getElementsByTagName("repeat") || []).filter((item: any) => item?.getAttribute('direction') === 'forward')
  1845. const firstRepeat: any = startRepeat?.length ? startRepeat[0] : null;
  1846. if (firstRepeat) {
  1847. let parentElement = firstRepeat?.parentNode
  1848. while (parentElement && parentElement.tagName !== 'measure') {
  1849. parentElement = parentElement.parentNode
  1850. }
  1851. state.timegapRepeatMeasureIndex = parentElement?.getAttribute('number') ? Number(parentElement?.getAttribute('number')) : 1;
  1852. }
  1853. for (const timeGap of timeGaps) {
  1854. const num: any = timeGap?.getAttribute('num'), den: any = timeGap?.getAttribute('den');
  1855. const startTime = num ? 60 / state.originSpeed * num * 4/den : 0;
  1856. state.evXmlBeginArr.push(startTime)
  1857. }
  1858. }
  1859. console.log('🚀 ~ evxml解析','有timegap:',hasTimeGap,'有times:',hasTimes,'timegap集合',state.evXmlBeginArr,'第一个timegap',state.evXmlBeginTime)
  1860. }
  1861. // if (!hasTimeGap && !hasTimes) {
  1862. // state.noTimes.push(xmlUrl)
  1863. // }
  1864. }
  1865. /**
  1866. * 兼容处理xml声部移调
  1867. * 打谱软件可能会自动处理移调,这类型的xml就不用通过程序移调了
  1868. * 没有通过软件处理的移调xml,才需要通过程序处理
  1869. * 判读规则:只处理独奏的,不处理合奏的,
  1870. * <instrument-name></instrument-name>标签的值为:Tenor Recorder(竖笛)、Panpipes(排箫)、Ocarina(陶笛)、Woodwind(葫芦丝)、空的和solo,需要程序处理移调
  1871. */
  1872. export const compatibleXmlPitchVoice = (xmlParse: any) => {
  1873. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1874. const partListNames = partNames.filter((item: any) => item?.textContent?.trim().toLocaleUpperCase() !== "COMMON");
  1875. if (partListNames.length == 1) {
  1876. const instrumentNames = Array.from(xmlParse.getElementsByTagName('instrument-name')) || [];
  1877. // @ts-ignore
  1878. const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
  1879. // console.log('instrument名称',instrumentName)
  1880. // 是否需要程序处理移调
  1881. let xmlNeedAdjustVoice = false;
  1882. switch (state.musicalCodeId) {
  1883. case 37:
  1884. case 38:
  1885. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('tenor recorder') ? true : false
  1886. break;
  1887. case 33:
  1888. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('panpipes') ? true : false
  1889. break;
  1890. case 34:
  1891. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('ocarina') ? true : false
  1892. break;
  1893. case 35:
  1894. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('woodwind') ? true : false
  1895. break;
  1896. case 39:
  1897. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('whistling') ? true : false
  1898. break;
  1899. default:
  1900. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') ? true : false
  1901. break;
  1902. }
  1903. // (window as any).xmlNeedAdjustVoice = xmlNeedAdjustVoice
  1904. // 管乐迷的曲子不需要上述判断,修改为都需要程序处理(保持和之前逻辑一致)
  1905. (window as any).xmlNeedAdjustVoice = true
  1906. }
  1907. }
  1908. // 筛选出这个音符中的值(比前一个音符时值大的值)
  1909. function fliterNotesTime(note:any, preTime:number):undefined|number {
  1910. // 音符可能涉及多遍歌词,所以这里要找到对应的times
  1911. if(note?.noteTimeInfo?.length){
  1912. const timeObj = note?.noteTimeInfo.find((value:any) => {
  1913. const beginTime = value?.begin*1000 || 0
  1914. return beginTime > preTime || Math.abs(beginTime - preTime)< 10 //差值在10毫秒之内
  1915. })
  1916. return timeObj?.begin*1000
  1917. }else{
  1918. return undefined
  1919. }
  1920. }