formateMusic.ts 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  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): string => {
  508. if (!xml) return "";
  509. // console.log('原始xml')
  510. //const detailId = state.examSongId + "";
  511. console.time('解析xml 耗时5')
  512. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  513. console.timeEnd('解析xml 耗时5')
  514. const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
  515. //const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");
  516. //state.partListNames = partListNames;
  517. Array.from(partList).forEach((part) => {
  518. let partListName = part.getElementsByTagName("part-name")?.[0]?.textContent?.trim();
  519. if (!state.canSelectTracks.includes(partListName)) {
  520. part.parentNode?.removeChild(part);
  521. }
  522. });
  523. // console.log(xmlParse)
  524. return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
  525. };
  526. // 倚音后连音线
  527. export const appoggianceFormate = (xmlParse: Document): Document => {
  528. if (!xmlParse) return xmlParse;
  529. const graces: any = xmlParse.querySelectorAll("grace");
  530. if (!graces.length) return xmlParse;
  531. const getNextElement = (el: HTMLElement): HTMLElement => {
  532. if (el.querySelector("grace")) {
  533. return getNextElement(el?.nextElementSibling as HTMLElement);
  534. }
  535. return el;
  536. };
  537. for (let grace of graces) {
  538. const notations = grace.parentElement?.querySelector("notations");
  539. if (notations && notations.querySelectorAll("slur").length > 1) {
  540. let nextEle: Element = getNextElement(grace.parentElement?.nextElementSibling as HTMLElement);
  541. if (nextEle && nextEle.querySelectorAll("slur").length > 0) {
  542. const slurNumber = Array.from(nextEle.querySelector("notations")?.children || []).map((el: Element) => {
  543. return el.getAttribute("number");
  544. });
  545. const slurs = notations.querySelectorAll("slur");
  546. for (let nota of slurs) {
  547. if (!slurNumber.includes(nota.getAttribute("number"))) {
  548. nextEle.querySelector("notations")?.appendChild(nota);
  549. }
  550. }
  551. }
  552. }
  553. }
  554. return xmlParse;
  555. };
  556. /** 根据ID获取最顶级ID */
  557. export const isWithinScope = (tree: any[], id: number): number => {
  558. if (!tree) return 0;
  559. let result = 0;
  560. for (const item of tree) {
  561. if (item.id === id) {
  562. result = item.id;
  563. break;
  564. }
  565. if (item.sysMusicScoreCategoriesList) {
  566. result = isWithinScope(item.sysMusicScoreCategoriesList, id);
  567. if (result > 0) {
  568. result = item.id;
  569. }
  570. if (result) break;
  571. }
  572. }
  573. return result;
  574. };
  575. class NoteList {
  576. notes: any[] = [];
  577. constructor(notes: any[]) {
  578. this.notes = notes;
  579. }
  580. public last() {
  581. return this.notes[this.notes.length - 1];
  582. }
  583. public list() {
  584. return this.notes;
  585. }
  586. }
  587. export const getNotesByid = (id: string): NoteList => {
  588. const notes = new NoteList(state.times.filter((item) => item.id === id));
  589. return notes;
  590. };
  591. /** 格式化当前曲谱缩放比例 */
  592. export const formatZoom = (num = 1) => {
  593. return num * state.zoom;
  594. };
  595. /** 妙极客多分轨的曲子,可能没有part-name标签,需要手动加上该标签 */
  596. export const xmlAddPartName = (xml: string) => {
  597. if (!xml) return "";
  598. console.time('解析xml 耗时')
  599. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  600. console.timeEnd('解析xml 耗时')
  601. const scoreParts = Array.from(xmlParse.getElementsByTagName("score-part"));
  602. for (const scorePart of scoreParts) {
  603. if (scorePart.getElementsByTagName("part-name").length === 0) {
  604. state.evxmlAddPartName = true;
  605. const name = scorePart.getAttribute("id") || "";
  606. const newPartName = `<part-name>${name}</part-name>`
  607. // scorePart.prepend(newPartName);
  608. scorePart.innerHTML = newPartName + scorePart.innerHTML;
  609. }
  610. if (scorePart.getElementsByTagName("part-name").length && !scorePart.getElementsByTagName("part-name")?.[0]?.textContent?.trim() ) {
  611. scorePart.getElementsByTagName("part-name")[0].textContent = scorePart.getAttribute("id") || "";
  612. }
  613. }
  614. xmlDocRef.value = xmlParse;
  615. return new XMLSerializer().serializeToString(xmlParse);
  616. }
  617. /** 格式化曲谱
  618. * 1.全休止符的小节,没有音符默认加个全休止符
  619. */
  620. export const formatXML = (xml: string, xmlUrl?: string, resourceType?: string): string => {
  621. if (!xml) return "";
  622. //console.time('解析xml 耗时7')
  623. // const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  624. const xmlParse = xmlDocRef.value && resourceType === 'init' ? xmlDocRef.value : new DOMParser().parseFromString(xml, "text/xml");
  625. //console.timeEnd('解析xml 耗时7')
  626. // 声调
  627. const fifths = xmlParse.getElementsByTagName("fifths");
  628. if (fifths && fifths.length) {
  629. // 是否是C调
  630. state.isCTone = fifths[0].textContent === '0'
  631. }
  632. const endings = Array.from(xmlParse.getElementsByTagName("ending"));
  633. for (const ending of endings) {
  634. // if (ending.getAttribute('type') === 'stop') {
  635. // // @ts-ignore
  636. // ending.parentNode?.removeChild(ending.parentNode?.getElementsByTagName('bar-style')[0])
  637. // }
  638. // @ts-ignore
  639. // ending.parentNode.parentNode?.removeChild(ending.parentNode)
  640. }
  641. const measures = Array.from(xmlParse.getElementsByTagName("measure"));
  642. state.firstMeasureNumber = measures[0] ? Number(measures[0].getAttribute('number') || 1) : 1;
  643. const minutes: any = xmlParse.getElementsByTagName("per-minute");
  644. let speeds: any = []
  645. for (const minute of minutes) {
  646. let measureSpeed = minute.textContent ? Number(minute.textContent) : 0;
  647. // 速度带附点,需要转换成不带附点的速度值
  648. // const hasSpeedDot = Array.from(minute?.parentElement?.children || []).some((item: any) => item?.tagName === 'beat-unit-dot')
  649. // measureSpeed = hasSpeedDot ? measureSpeed + measureSpeed/2 : measureSpeed;
  650. if (minute.textContent && measureSpeed) {
  651. speeds.push(Number(measureSpeed))
  652. }
  653. // if (hasSpeedDot && measureSpeed) {
  654. // minute.textContent = measureSpeed
  655. // const dotDom = minute?.parentElement.querySelector('beat-unit-dot')
  656. // minute?.parentElement?.removeChild(dotDom)
  657. // }
  658. }
  659. speeds = [...new Set(speeds)]
  660. const hasVaryingSpeed = speeds.length > 1 ? true : false
  661. // 如果后台没有设置速度,默认取xml速度,如果xml也没有速度,默认赋值100
  662. if (state.originSpeed === 0) {
  663. state.originSpeed = speeds[0] ? speeds[0] : 100;
  664. state.speed = state.originSpeed;
  665. }
  666. // 赋值谱面速度节拍器,没有的时候 以后台传入的为准
  667. const metronomeXml = xmlParse.getElementsByTagName('metronome')?.[0]
  668. const beatUnit = metronomeXml?.getElementsByTagName('beat-unit')?.[0]?.textContent || ''
  669. if(beatUnit){
  670. const beatUnitDot = metronomeXml?.getElementsByTagName('beat-unit-dot')?.[0]
  671. state.speedBeatUnit = beatUnitTo(beatUnit, !!beatUnitDot)
  672. }
  673. // 如果谱面和小节都没有打速度,osmd设置的小节速度默认取后台设置的速度
  674. if (speeds.length === 0) {
  675. ;(window as any).baseMeasureSpeed = state.originSpeed
  676. } else {
  677. // 当前谱面的速度转为4分音符速度 因为我们速度比例转为4分音符了
  678. state.originAudioPlayRate = speedBeatTo({unit:state.speedBeatUnit, speed:speeds[0]}, "1/4") / state.originSpeed
  679. }
  680. console.log('是否是变速的曲子:',hasVaryingSpeed,speeds)
  681. let repeats: any = [];
  682. if (state.partIndex === 999) {
  683. repeats = Array.from(xmlParse.querySelectorAll('repeat')) || [];
  684. } else {
  685. const hasCommon = xmlParse.querySelectorAll('part-name')?.[0]?.textContent === 'common';
  686. const currentTrackIndex = hasCommon ? state.partIndex + 1 : state.partIndex;
  687. repeats = Array.from(xmlParse.querySelectorAll('part')?.[currentTrackIndex]?.querySelectorAll('repeat')) || [];
  688. }
  689. compatibleXmlPitchVoice(xmlParse);
  690. // 获取作词、作曲家
  691. getComposer(xmlParse);
  692. // 处理重复小节信息
  693. parseXmlToRepeat(repeats)
  694. // 解析处理evxml
  695. if (state.isEvxml) {
  696. analyzeEvxml(xmlParse, xmlUrl);
  697. customizationXml(xmlParse);
  698. }
  699. // const words: any = xmlParse.getElementsByTagName("words");
  700. // for (const word of words) {
  701. // if (word && word.textContent?.trim() === "筒音作5") {
  702. // word.setAttribute('y',260)
  703. // 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>'
  704. // }
  705. // }
  706. // console.log(11111,Array.from(xmlParse.getElementsByTagName("staffline")),Array.from(xmlParse.getElementsByTagName("words")))
  707. let speed = -1
  708. let beats = -1;
  709. let beatType = -1;
  710. // 前面小节的拍子
  711. let preBeats: number = 4;
  712. let preBeatType: number = 4;
  713. let baseDivisions: number = 256;
  714. // 小节中如果没有节点默认为休止符
  715. for (const measure of measures) {
  716. if (beats === -1 && measure.getElementsByTagName("beats").length) {
  717. beats = parseInt(measure.getElementsByTagName("beats")[0].textContent || "4");
  718. }
  719. if (beatType === -1 && measure.getElementsByTagName("beat-type").length) {
  720. beatType = parseInt(measure.getElementsByTagName("beat-type")[0].textContent || "4");
  721. }
  722. if (speed === -1 && measure.getElementsByTagName('per-minute').length) {
  723. speed = Number(measure.getElementsByTagName('per-minute')[0]?.textContent)
  724. }
  725. // 当前小节的拍数
  726. const currentBeats = measure.getElementsByTagName("beats").length ? measure.getElementsByTagName("beats")[0]?.textContent : preBeats;
  727. const currentBeatType = measure.getElementsByTagName("beat-type").length ? measure.getElementsByTagName("beat-type")[0]?.textContent : preBeatType;
  728. preBeats = Number(currentBeats);
  729. preBeatType = Number(currentBeatType);
  730. const divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || String(baseDivisions));
  731. baseDivisions = divisions
  732. // 如果note节点里面有space节点,并且没有duration节点,代表这是一个空白节点,需要删除
  733. if (measure.getElementsByTagName("note").length && state.isEvxml) {
  734. const noteList = Array.from(measure.getElementsByTagName("note")) || [];
  735. noteList.forEach((note: any) => {
  736. // if (note.getElementsByTagName("space").length && !note.getElementsByTagName("duration").length) {
  737. // measure.removeChild(note);
  738. // }
  739. // 非倚音音符
  740. if (!note.getElementsByTagName("grace").length) {
  741. if (!note.getElementsByTagName("duration").length || (note.getElementsByTagName("duration").length && note.getElementsByTagName("duration")[0]?.textContent == 0)) {
  742. measure.removeChild(note);
  743. }
  744. }
  745. });
  746. }
  747. // 如果有特殊中文速度文本,需要删除
  748. const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  749. if (measure.getElementsByTagName("words").length && state.isEvxml) {
  750. const wordList = Array.from(measure.getElementsByTagName("words")) || [];
  751. wordList.forEach((word: any) => {
  752. // TODO:删除妙极客曲子无意义的words
  753. // wordArr?.push(word?.textContent)
  754. if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
  755. measure.removeChild(word.parentNode.parentNode);
  756. // deleteWordArr?.push(word?.textContent)
  757. }
  758. // if(hideSpeedWords.includes(word?.textContent) && word?.parentNode?.parentNode) {
  759. // measure.removeChild(word.parentNode.parentNode);
  760. // }
  761. })
  762. }
  763. if (measure.getElementsByTagName("note").length === 0) {
  764. const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
  765. if (forwardTimeElement) {
  766. forwardTimeElement.textContent = "0";
  767. }
  768. measure.innerHTML =
  769. measure.innerHTML +
  770. `
  771. <note>
  772. <rest measure="yes"/>
  773. <duration>${divisions * beats}</duration>
  774. <voice>1</voice>
  775. <type>whole</type>
  776. </note>`;
  777. } else if (state.musicRenderType !== 'staff') {
  778. transferJianNote(measure, divisions, preBeats, preBeatType)
  779. }
  780. }
  781. xmlDocRef.value = xmlParse;
  782. return new XMLSerializer().serializeToString(xmlParse);
  783. };
  784. /** 获取所有音符的时值,以及格式化音符 */
  785. export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
  786. const customNoteRealValue = customData.customNoteRealValue;
  787. const customNoteCurrentTime = customData.customNoteCurrentTime;
  788. const detailId = state.examSongId + "";
  789. const partIndex = state.partIndex + "";
  790. //let fixtime = browserInfo.huawei ? 0.08 : 0; //getFixTime()
  791. let fixtime = 0;
  792. const allNotes: any[] = [];
  793. const allNoteId: string[] = [];
  794. const allMeasures: any[] = [];
  795. const { originSpeed: baseSpeed } = state;
  796. let preMeasureNumber = 0;
  797. const formatRealKey = (realKey: number, detail: any) => {
  798. // 不是管乐迷, 不处理
  799. // if (state.appName !== "GYM") return realKey;
  800. // 长笛的LEVEL 2-5-1条练习是泛音练习,以每小节第一个音的指法为准,高音不变变指法。
  801. const olnyOneIds = ["906"];
  802. if (olnyOneIds.includes(state.cbsExamSongId)) {
  803. return detail.measures[0]?.realKey || realKey;
  804. }
  805. // 圆号的LEVEL 2-5条练习是泛音练习,最后四小节指法以连音线第一个小节为准
  806. const olnyOneIds2 = ["782", "784"];
  807. if (olnyOneIds2.includes(state.cbsExamSongId)) {
  808. const measureNumbers = [14, 16, 30, 32];
  809. if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
  810. return allNotes[allNotes.length - 1]?.realKey || realKey;
  811. }
  812. }
  813. // 2-6 第三小节指法按照第一个音符显示
  814. const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
  815. if (filterIds.includes(state.cbsExamSongId)) {
  816. if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
  817. return detail.measures[0]?.realKey || realKey;
  818. }
  819. }
  820. return realKey;
  821. };
  822. if (!osmd.cursor) return [];
  823. const iterator: any = osmd.cursor.Iterator;
  824. // console.log("🚀 ~ iterator:", iterator)
  825. console.time("音符跑完时间");
  826. let i = 0;
  827. let si = 0;
  828. let measures: any[] = [];
  829. let stepSpeeds: number[] = [];
  830. /** 弱起时间 */
  831. let difftime = 0;
  832. let usetime = 0;
  833. let relaMeasureLength = 0;
  834. let beatUnit = "quarter";
  835. let gradualSpeed;
  836. let gradualChange: GradualChange | undefined;
  837. let gradualChangeIndex = 0;
  838. let totalMultipleRestMeasures = 0;
  839. let multipleRestMeasures = 0;
  840. let staveNoteIndex = 0;
  841. let staveIndex = 0;
  842. let xmlMp3BeatFixTime = 0 // xml上节拍器的时间
  843. let preNoteEndTime = 0; // 上一个音符的结束时间
  844. let preNoteMeasureNumber: any = null; // 上一个小节的number值
  845. let currentRealTempo: any = {}; // 当前小节的速度与拍号信息
  846. const _notes = [] as any[];
  847. if (state.gradualTimes) {
  848. console.log("后台设置的渐慢小节时间", state.gradual, state.gradualTimes);
  849. }
  850. let currentTimeStamp = iterator.currentTimeStamp.RealValue;
  851. const currentTimes = [] as any[];
  852. let isSetNextNoteReal = false;
  853. let differFrom = 0;
  854. // let testIdx = 0;
  855. let repeatIdx = 0; // 循环的次数
  856. /**
  857. * 当多选声部的时候 ,取选择的第一个声部
  858. * 总谱渲染时,需要取第一个渲染的声轨名字,canSelectTracks返回的声轨名字可能不是第一个,顺序有问题,需要用state.osmd.Sheet.Instruments
  859. */
  860. // const firstTrackName = state.combinePartIndexs.length>1 ? state.partListNames[state.combinePartIndexs[0]] : state.canSelectTracks[0] || "";
  861. const firstTrackName = state.combinePartIndexs.length>1 ? state.partListNames[state.combinePartIndexs[0]] : (state.osmd.Sheet.Instruments[0].Name || state.osmd.Sheet.Instruments[0].NameLabel.text || "");
  862. const currentTrackIndex = state.isCombineRender && state.combinePartIndexs.length > 1 ? state.combinePartIndexs[0] : 0;
  863. while (!iterator.EndReached) {
  864. // console.log({ ...iterator });
  865. /** 多声轨合并显示,当前音符的时值取所有声轨中的最小值 */
  866. if (state.isCombineRender) {
  867. iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
  868. const trackName = state.isEvxml && state.evxmlAddPartName ? item.parentVoice.parent.IdString || '' : item.parentVoice.parent.Name || '';
  869. return trackName?.trim() === firstTrackName
  870. });
  871. }
  872. // 多轨合并显示,或者单轨多声部的情况,需要过滤掉下半边声部的音符
  873. if ( ((!state.isCombineRender && state.isSingleMutliTrack) || state.isCombineRender) && iterator.currentVoiceEntries.length) {
  874. iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
  875. return item.ParentVoice.voiceId === 1
  876. });
  877. }
  878. let minIndex = 0, elRealValue = 0
  879. for (let index = 0; index < iterator.currentVoiceEntries.length; index++) {
  880. const element = iterator.currentVoiceEntries[index];
  881. if (element.isGrace) {
  882. if (minIndex == index && minIndex == 0) {
  883. minIndex = iterator.currentVoiceEntries.length > 1 ? 1 : 0
  884. }
  885. continue
  886. }
  887. if (element.notes[0].length.realValue < elRealValue) {
  888. minIndex = index
  889. }
  890. // console.log(element.notes[0].SourceMeasure.MeasureNumberXML,element.notes[0].playbackInstrumentId,element.ParentVoice.voiceId)
  891. elRealValue = element.notes[0].length.realValue
  892. }
  893. if (minIndex !== 0 && state.isCombineRender && iterator.currentVoiceEntries[minIndex]) {
  894. iterator.currentVoiceEntries[minIndex].Notes[0].NoteToGraphicalNoteObjectId = iterator.currentVoiceEntries?.[0].Notes[0].NoteToGraphicalNoteObjectId;
  895. }
  896. const voiceEntries = iterator.currentVoiceEntries?.[minIndex] ? [iterator.currentVoiceEntries?.[minIndex]] : [];
  897. let currentVoiceEntries: any[] = [];
  898. // 多分轨,当前小节最大音符数量
  899. let maxNoteNum = 0;
  900. // iterator.currentMeasure?.verticalMeasureList?.forEach((item: any) => maxNoteNum = Math.max(maxNoteNum, item?.staffEntries?.length || 0))
  901. maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
  902. // console.log(iterator.currentMeasure.MeasureNumberXML,maxNoteNum,iterator.currentMeasure?.verticalSourceStaffEntryContainers.length)
  903. // 单声部多声轨
  904. if (state.multitrack > 0) {
  905. currentVoiceEntries = [...iterator.CurrentVoiceEntries];
  906. } else {
  907. currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
  908. return n && n?.ParentVoice?.VoiceId != 1;
  909. });
  910. }
  911. let currentTime = 0;
  912. let isDouble = false;
  913. let isMutileSubject = false;
  914. if (currentVoiceEntries.length && !isSetNextNoteReal) {
  915. isDouble = true;
  916. let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
  917. notes.push(...n.Notes);
  918. return notes;
  919. }, [] as any);
  920. voiceNotes = voiceNotes.filter((note: any) => !note.IsGraceNote)
  921. voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
  922. currentTime = voiceNotes?.[0]?.length?.realValue || 0;
  923. if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
  924. const min = voiceNotes[0]?.length?.realValue || 0;
  925. const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
  926. differFrom = max - min;
  927. isSetNextNoteReal = differFrom === 0 ? false : true;
  928. }
  929. }
  930. // 多声部上下音符没对齐,光标多走一拍
  931. if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
  932. isMutileSubject = true;
  933. }
  934. if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
  935. isDouble = true;
  936. currentTime = differFrom;
  937. isSetNextNoteReal = false;
  938. differFrom = 0;
  939. }
  940. currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
  941. currentTimeStamp = iterator.currentTimeStamp.realValue;
  942. for (const v of voiceEntries) {
  943. let note = v.notes[0];
  944. if (note.IsGraceNote) {
  945. // 如果是装饰音, 取不是装饰音的时值
  946. const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace);
  947. if (!voice) {
  948. continue;
  949. }
  950. note = voice.notes[0];
  951. }
  952. note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
  953. // 有倚音
  954. if (note?.voiceEntry?.isGrace) {
  955. isDouble = true;
  956. let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
  957. notes.push(...n.notes);
  958. return notes;
  959. }, []);
  960. ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
  961. currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
  962. }
  963. if (state.multitrack > 0 && currentTime > note.length.realValue) {
  964. currentTime = note.length.realValue;
  965. }
  966. note.maxNoteNum = maxNoteNum;
  967. note.trackIndex = minIndex;
  968. currentRealTempo = iterator.currentMeasure.tempoExpressions.length ? iterator.currentMeasure.tempoExpressions.find((item: any) => item?.InstantaneousTempo?.isMetronomeMark)?.InstantaneousTempo || currentRealTempo : currentRealTempo;
  969. const { beatUnit="quarter", dotted=false, tempoInBpm=state.originSpeed } = currentRealTempo
  970. const speedBeatUnit = beatUnitTo(beatUnit, dotted)
  971. _notes.push({
  972. measureNum: note?.sourceMeasure?.MeasureNumberXML,
  973. note,
  974. iterator: { ...iterator },
  975. currentTime,
  976. isDouble,
  977. isMutileSubject,
  978. // measuresTempoInBPM: note?.sourceMeasure?.tempoInBPM,
  979. // 转换成1/4拍的速度
  980. measuresTempoInBPM: speedBeatTo({unit: speedBeatUnit || "1/4",speed: tempoInBpm || 0}, `1/4`),
  981. speedBeatUnit, // 当前谱面小节的速度对应的是几分音符
  982. currentRealTempo
  983. });
  984. }
  985. iterator.moveToNextVisibleVoiceEntry(false);
  986. // 从头开始循环,repeatIdx标记+1
  987. if (iterator.backJumpOccurred) {
  988. repeatIdx += 1;
  989. }
  990. iterator.repeatIdx = repeatIdx;
  991. // console.log('小节',testIdx,iterator.repeatIdx,iterator.EndReached,iterator.currentMeasureIndex,iterator.backJumpOccurred,iterator.forwardJumpOccurred)
  992. // testIdx += 1;
  993. }
  994. // 是否是变速的曲子
  995. const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
  996. console.log('变速曲子',hasVaryingSpeed, _notes)
  997. let noteIds: any = [];
  998. // let voicesBBox: any = null;
  999. for (let { note, iterator, currentTime, isDouble, isMutileSubject, speedBeatUnit, measuresTempoInBPM } of _notes) {
  1000. if (note) {
  1001. if (preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  1002. si = 0
  1003. }
  1004. if (si === 0 && preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  1005. preMeasureNumber = note?.sourceMeasure?.MeasureNumberXML
  1006. allMeasures.push(note.sourceMeasure);
  1007. }
  1008. // if (si === 0 && state.isSpecialBookCategory) {
  1009. // for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
  1010. // if (expression?.InstantaneousTempo?.beatUnit) {
  1011. // // 取最后一个有效的tempo
  1012. // beatUnit = expression.InstantaneousTempo.beatUnit;
  1013. // }
  1014. // }
  1015. // }
  1016. // 判断是否是同一小节
  1017. if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
  1018. staveNoteIndex++
  1019. } else {
  1020. // staveIndex不同,重新赋值
  1021. staveIndex = note.sourceMeasure?.MeasureNumberXML
  1022. staveNoteIndex = 0
  1023. }
  1024. let measureSpeed = note.sourceMeasure.tempoInBPM;
  1025. const { metronomeNoteIndex } = iterator.currentMeasure;
  1026. if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
  1027. measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
  1028. }
  1029. // 当前的分轨
  1030. let activeVerticalMeasureList: any = [];
  1031. /**
  1032. * bug: #9959
  1033. * 多分轨合并展示,第一分轨又可能获取不到对应的音符,需要在当前小节中音符最多的分轨中去查找音符
  1034. */
  1035. // if (state.isCombineRender) {
  1036. // const allTrackList = note.sourceMeasure.verticalMeasureList;
  1037. // let maxIdx = 0, maxNote = 0;
  1038. // allTrackList.forEach((item: any, index: number) => {
  1039. // if (item?.vfVoices['1']?.tickables?.length > maxNote) {
  1040. // maxIdx = index
  1041. // maxNote = item?.vfVoices['1']?.tickables?.length
  1042. // }
  1043. // })
  1044. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[maxIdx]] || [];
  1045. // } else {
  1046. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
  1047. // }
  1048. // 合并展示某些分轨,需要把展示的分轨筛选出来
  1049. if (state.isCombineRender && note.sourceMeasure.verticalMeasureList.length) {
  1050. note.sourceMeasure.verticalMeasureList = note.sourceMeasure?.verticalMeasureList.filter((item: any) => state.canSelectTracks.includes(item?.parentStaff?.parentInstrument.Name?.trim()))
  1051. }
  1052. activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentTrackIndex]] || [];
  1053. // 某些情况下,合并显示的妙极客曲子,note.sourceMeasure?.verticalMeasureList可能为空数组
  1054. if (state.isCombineRender && state.isEvxml && note.sourceMeasure?.verticalMeasureList.length === 0) {
  1055. activeVerticalMeasureList = osmd.GraphicSheet.MeasureList.find((item: any) => item[0]?.MeasureNumber === note.sourceMeasure.MeasureNumberXML) || [];
  1056. }
  1057. let currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
  1058. /**
  1059. * TODO:多分轨合并的小节,音符可能没有id,此时就去其它分轨找
  1060. */
  1061. const vmLength = note.sourceMeasure?.verticalMeasureList?.length
  1062. let currentVmIndex = 0;
  1063. let hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1064. while (!hasSvgElement && vmLength > 1 && currentVmIndex <= vmLength - 1 && currenrtVfVoices !== null) {
  1065. currentVmIndex += 1;
  1066. activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentVmIndex]] || [];
  1067. currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
  1068. hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1069. }
  1070. const { realValue } = iterator.currentTimeStamp;
  1071. const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(
  1072. iterator.currentMeasure.activeTimeSignature,
  1073. iterator.currentMeasure.duration
  1074. );
  1075. let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
  1076. if (customNoteRealValue[i]) {
  1077. // console.log(NoteRealValue, customNoteRealValue[i])
  1078. NoteRealValue = customNoteRealValue[i];
  1079. }
  1080. if (isDouble && currentTime > 0) {
  1081. if (currentTime != NoteRealValue) {
  1082. // console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
  1083. NoteRealValue = currentTime;
  1084. }
  1085. }
  1086. // note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
  1087. // 管乐迷,按自定义按读取到的音符时值
  1088. if (customNoteCurrentTime) {
  1089. if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
  1090. // console.log(NoteRealValue, currentTimes[i + 1])
  1091. NoteRealValue = currentTimes[i + 1];
  1092. }
  1093. }
  1094. let relativeTime = usetime;
  1095. // 妙极客的曲子,修复有的音符有times,有的音符没有times导致的,累计时长错误问题
  1096. if (state.isEvxml && relativeTime < preNoteEndTime - fixtime) {
  1097. relativeTime = preNoteEndTime - fixtime
  1098. }
  1099. let beatSpeed = 0;
  1100. // 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度,否则mp3速度不对
  1101. // if (measureSpeed !== baseSpeed && !hasVaryingSpeed) {
  1102. // beatSpeed = baseSpeed || measureSpeed || 100
  1103. // } else {
  1104. // beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  1105. // }
  1106. // 计算音符时值,使用转换成1/4的速度计算
  1107. beatSpeed = measuresTempoInBPM;
  1108. // let beatSpeed = measureSpeed || baseSpeed
  1109. beatSpeed = beatSpeed / state.originAudioPlayRate;
  1110. // 如果有节拍器,需要将节拍器的时间算出来
  1111. if (i === 0) {
  1112. if(state.isOpenMetronome){
  1113. fixtime += getFixTime(beatSpeed);
  1114. state.fixtime = fixtime;
  1115. }
  1116. // 存储mp3节拍器时间
  1117. xmlMp3BeatFixTime = getFixTime(beatSpeed)
  1118. // console.log("fixtime:", fixtime, '速度:', beatSpeed, "state.isSpecialBookCategory:", state.isSpecialBookCategory, 'state.isOpenMetronome:', state.isOpenMetronome);
  1119. }
  1120. let gradualLength = 0;
  1121. // let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  1122. let speed = measureSpeed ? measureSpeed : baseSpeed;
  1123. gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
  1124. gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
  1125. if (!gradualSpeed || gradualSpeed.length < 2) {
  1126. gradualSpeed = createSpeedInfo(gradualChange, speed);
  1127. }
  1128. // console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
  1129. const measureListIndex = iterator.currentMeasure.measureListIndex;
  1130. // 计算相差时间按照比例分配到所有音符上
  1131. if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
  1132. const withInRangeNote = state.gradual.find((item, index) => {
  1133. const nextItem: any = state.gradual[index + 1];
  1134. return (
  1135. item[0].measureIndex <= measureListIndex &&
  1136. item[1]?.measureIndex! >= measureListIndex &&
  1137. (!nextItem || nextItem?.[0].measureIndex !== measureListIndex)
  1138. );
  1139. });
  1140. const [first, last] = withInRangeNote || [];
  1141. if (first && last) {
  1142. // 小节数量
  1143. const continuous = last.measureIndex - first.measureIndex;
  1144. // 开始小节内
  1145. const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
  1146. // 结束小节内
  1147. const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
  1148. // 范围内小节
  1149. const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
  1150. if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
  1151. const startTime = state.gradualTimes[first.measureIndex];
  1152. const endTime = state.gradualTimes[last.measureIndex];
  1153. if (startTime && endTime) {
  1154. const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
  1155. const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
  1156. gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. const _noteLength = NoteRealValue;
  1162. // 当前音符的持续时长,当前音符的RealValue值*拍数*(60/后台设置的基准速度)
  1163. let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1164. // 小节时长
  1165. const measureLength = vRealValue * 4 * (60 / beatSpeed);
  1166. // console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
  1167. // console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
  1168. /**
  1169. * TODO:摇篮曲-人音-排箫(1788501975122489346),第12小节音符持续时间特殊处理
  1170. */
  1171. if (['1788501975122489346','1788502467554750466'].includes(state.cbsExamSongId)) {
  1172. if (i == 13) {
  1173. noteLength = noteLength / 2;
  1174. }
  1175. if (i == 44) {
  1176. noteLength = noteLength * 6;
  1177. }
  1178. if (i == 56) {
  1179. noteLength = noteLength * 4;
  1180. }
  1181. }
  1182. usetime += noteLength;
  1183. relaMeasureLength += noteLength;
  1184. let relaEndtime = noteLength + relativeTime;
  1185. // console.log('relaEndtime',noteLength, relativeTime)
  1186. const fixedKey = note.fixedKey || 0;
  1187. // const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
  1188. //const svgElement = currenrtVfVoices?.tickables[staveNoteIndex];
  1189. // 过滤掉ghostnote
  1190. const filterTickables = currenrtVfVoices?.tickables?.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
  1191. const svgElement = filterTickables?.[staveNoteIndex];
  1192. // console.log('si',si,i)
  1193. // console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
  1194. if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
  1195. i++
  1196. continue;
  1197. }
  1198. // console.log(iterator.currentMeasure)
  1199. // 如果是弱起就补齐缺省的时长,midi音频不需要考虑弱起
  1200. if (i === 0 && !state.isAppPlay) {
  1201. let _firstMeasureRealValue = 0;
  1202. const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
  1203. //计算第一个小节里面的音符时值是否等于整个小节的时值
  1204. staffEntries.forEach((_a: any) => {
  1205. // 需要过滤掉倚音音符
  1206. const matchNote = _a?.sourceStaffEntry?.voiceEntries?.length > 1 ? _a?.sourceStaffEntry?.voiceEntries.find((item: any) => !item.isGrace) : _a?.sourceStaffEntry?.voiceEntries?.[0]
  1207. if (matchNote?.notes?.[0]?.length?.realValue) {
  1208. _firstMeasureRealValue += matchNote.notes[0].length.realValue;
  1209. }
  1210. });
  1211. if (_firstMeasureRealValue < vRealValue) {
  1212. // console.log(_firstMeasureRealValue, vRealValue)
  1213. // 如果是弱起,将整个小节的时值减去该小节所有音符相加的时值,就是缺省的时值
  1214. difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1215. }
  1216. /**
  1217. * 管乐迷,部分弱起的曲目,mp3制作不标准,没有按照补齐弱起后的时间进行制作,需要单独处理
  1218. * 2670
  1219. */
  1220. if (["2670"].includes(state.cbsExamSongId)) {
  1221. // fixtime -= _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1222. } else {
  1223. if (difftime > 0 && !state.isEvxml) {
  1224. fixtime += difftime;
  1225. state.fixtime = fixtime;
  1226. }
  1227. }
  1228. // 管乐迷 diff获取不准确时, 弱起补齐
  1229. if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
  1230. // difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1231. // fixtime += difftime;
  1232. }
  1233. // 如果是evxml,fixtime取读取xml的值
  1234. if (state.isEvxml) {
  1235. fixtime = state.evXmlBeginTime ? state.evXmlBeginTime : fixtime
  1236. state.fixtime = fixtime
  1237. }
  1238. console.log('节拍器时间',fixtime,state.evXmlBeginTime)
  1239. }
  1240. let stave = activeVerticalMeasureList[0]?.stave;
  1241. if (note.sourceMeasure.multipleRestMeasures) {
  1242. totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures;
  1243. multipleRestMeasures = 0;
  1244. }
  1245. if (multipleRestMeasures < totalMultipleRestMeasures) {
  1246. if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
  1247. multipleRestMeasures++;
  1248. } else {
  1249. multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
  1250. }
  1251. } else {
  1252. if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
  1253. multipleRestMeasures = 0;
  1254. totalMultipleRestMeasures = 0;
  1255. } else {
  1256. multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
  1257. }
  1258. }
  1259. // console.log(note.tie)
  1260. // console.log('👀看看endtime', duration, relaEndtime, fixtime, i)
  1261. // console.log('频率',note?.pitch?.frequency,i)
  1262. /**
  1263. * evxml的曲子,如果曲谱xml中带有times信息,则音符时值优先取times中的值
  1264. * 曲子:1795013295024062466(春暖花开),如果音符有times信息,休止符没有times信息,此种规则是认为休止符不参与时值计算的,需要过滤掉该休止符
  1265. */
  1266. let evNoteStartTime = 0, evNoteEndTime = 0;
  1267. if (state.isEvxml && note?.noteTimeInfo?.length === 0 && state.xmlHasTimes ) {
  1268. // 找出这个音符前面音符的结束时间
  1269. let preNoteTImes = allNotes[allNotes.length - 1]?.endtime*1000
  1270. if(!preNoteTImes){
  1271. //如果前一个音符没有结束时间,证明这个音符是第一个音符没有打时间,当有timegap以fixtime当开始时间(1795013294269087745),当第一个小节有times这个往前奏里面找补(1795013306436763649)
  1272. preNoteTImes = (state.evXmlBeginArr.length>0 ? fixtime : Math.max(fixtime - noteLength, 0))*1000
  1273. }
  1274. // 找出这个音符后面音符的开始时间
  1275. let nextI = i
  1276. let nextNoteTimes
  1277. // 多个连续的没有打时间的音符 需要平分时值
  1278. const notesRatio = []
  1279. while (!nextNoteTimes && nextI<_notes.length) {
  1280. notesRatio.push(_notes[nextI].note.length.realValue)
  1281. nextI++
  1282. if(_notes[nextI]?.note){ // 有可能_notes里面没有这个音符
  1283. nextNoteTimes = fliterNotesTime(_notes[nextI].note, preNoteTImes)
  1284. }
  1285. }
  1286. // 当最后音符就是没有打时间的音符,可能nextNoteTimes时间找不到时候取上个音符的结束时间加上这个音符的时间
  1287. if(!nextNoteTimes){
  1288. nextNoteTimes = preNoteTImes + noteLength*1000
  1289. }
  1290. // 判断有没有首位连续 首位连续的时候删掉这个音符
  1291. const allowRange = Math.abs(nextNoteTimes - preNoteTImes)< 10;
  1292. if (allowRange) {
  1293. note.maxNoteNum = note.maxNoteNum - 1;
  1294. // 唱名时间补齐,当删除这个音符的时候,上个音符的持续时间要加上这个音符的时间
  1295. allNotes[allNotes.length - 1].noteLengthTime += noteLength
  1296. i++
  1297. continue;
  1298. }else{
  1299. // 当多个连续的休止符没有打时间的时候 根据音符平均分配
  1300. if(notesRatio.length > 1){
  1301. const sum = notesRatio.reduce((acc:number, curr:number) => acc + curr, 0)
  1302. nextNoteTimes = (nextNoteTimes - preNoteTImes) * notesRatio[0] / sum + preNoteTImes
  1303. }
  1304. evNoteEndTime = nextNoteTimes/1000
  1305. evNoteStartTime = preNoteTImes/1000
  1306. // 当这个音符计算出来的时值大于本身这个音符的时值时候,取这个音符的长度,防止有前奏和间奏的时候,计算音符持续时长过长
  1307. if(evNoteEndTime - evNoteStartTime > noteLength){
  1308. evNoteEndTime = evNoteStartTime + noteLength
  1309. }
  1310. if (evNoteStartTime) {
  1311. relativeTime = evNoteStartTime - fixtime
  1312. }
  1313. }
  1314. }
  1315. if (state.isEvxml && note?.noteTimeInfo?.length ) {
  1316. let idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0;
  1317. // 如果是合并的小节的休止符
  1318. if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
  1319. const customRestId = `rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`;
  1320. idx = noteIds.filter((item: any) => item === customRestId)?.length || 0;
  1321. }
  1322. evNoteStartTime = note?.noteTimeInfo[idx]?.begin
  1323. evNoteEndTime = note?.noteTimeInfo[idx]?.end
  1324. if (evNoteStartTime) {
  1325. relativeTime = evNoteStartTime - fixtime
  1326. // usetime = evNoteStartTime - fixtime
  1327. }
  1328. // usetime = evNoteStartTime - fixtime
  1329. }
  1330. svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
  1331. // 如果是合并的休止小节,是没有渲染音符的,所以没有svgElement对象,也就没有id,此时需要添加自定义的一个id进度,便于多遍循环时,找到对应的noteTimeInfo里面的时间信息
  1332. if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
  1333. noteIds.push(`rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`)
  1334. }
  1335. // 如果该音符包含倚音,添加标记
  1336. let hasGraceNote = false;
  1337. if (svgElement?.modifiers?.length) {
  1338. hasGraceNote = svgElement?.modifiers.some((item: any) => item?.attrs?.type === "GraceNoteGroup")
  1339. }
  1340. const filterRepeatIdx = allNotes.filter((item: any) => item.noteId === note.NoteToGraphicalNoteObjectId).length
  1341. const nodeDetail = {
  1342. trackIndex: note.trackIndex, // 当前的音符属于第几条分轨
  1343. isStaccato: note.voiceEntry.isStaccato(),
  1344. isRestFlag: note.isRestFlag,
  1345. // noteId: note.NoteToGraphicalNoteObjectId || `restNote${note.sourceMeasure.MeasureNumberXML}`,
  1346. noteId: note.NoteToGraphicalNoteObjectId,
  1347. measureListIndex: note.sourceMeasure.measureListIndex,
  1348. MeasureNumberXML: note.sourceMeasure.MeasureNumberXML, // 当前的小节数,(从1开始)
  1349. _noteLength: _noteLength,
  1350. svgElement: svgElement,
  1351. frequency: note?.pitch?.frequency || -1,
  1352. nextFrequency: note?.pitch?.nextFrequency || -1,
  1353. prevFrequency: note?.pitch?.prevFrequency || -1,
  1354. difftime,
  1355. octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
  1356. speed,
  1357. beatSpeed,
  1358. i,
  1359. si,
  1360. stepSpeeds,
  1361. measureOpenIndex: allMeasures.length - 1,
  1362. measures,
  1363. tempoInBPM: note.sourceMeasure.tempoInBPM,
  1364. measureLength,
  1365. relaMeasureLength,
  1366. id: svgElement?.attrs.id,
  1367. hasGraceNote,
  1368. note: note.halfTone + 12, // see issue #224
  1369. fixtime, // 弱起补充的时间
  1370. relativeTime: retain(relativeTime),
  1371. time: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + fixtime), // 开始播放的时间
  1372. endtime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + fixtime), // 播放完成的时间
  1373. relaEndtime: retain(relaEndtime),
  1374. realValue,
  1375. halfTone: note.halfTone,
  1376. noteElement: note,
  1377. fixedKey,
  1378. realKey: 0,
  1379. duration: 0,
  1380. formatLyricsEntries: formatLyricsEntries(note),
  1381. stave,
  1382. firstVerticalMeasure: activeVerticalMeasureList[0],
  1383. noteLength: 1,
  1384. //osdmContext: osmd,
  1385. // speedbeatUnit: beatUnit,
  1386. speedBeatUnit, // 当前谱面小节的速度对应的是几分音符
  1387. multipleRestMeasures: multipleRestMeasures, // 当前合并小节的索引,从1开始到当前的totalMultipleRestMeasures结束,
  1388. totalMultipleRestMeasures, // 当前小节总的合并小节数
  1389. measureSpeed, // 小节速度
  1390. maxNoteNum: note.maxNoteNum, // 当前小节音符最多的分轨的音符数量
  1391. // repeatIdx: iterator.repeatIdx || 0, // 标记是第几遍循环,从0开始
  1392. repeatIdx: filterRepeatIdx,
  1393. noteLengthTime: noteLength, //当前音符时长
  1394. xmlNoteTime: 0, // xml上音符开始时间 唱名用
  1395. xmlNoteEndTime: 0, //xml上音符结束时间 唱名用
  1396. xmlMp3BeatFixTime, //xml上节拍器的时间
  1397. notBeatFixtime: state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime, // 不含节拍器的fixtime值 唱名用
  1398. notBeatTime: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)), // 不含节拍器的 音符开始时间
  1399. notBeatEndTime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)), // 不含节拍器的 音符结束时间
  1400. frequencyList: [note?.pitch?.frequency || -1], // 如果是和弦音符,需要添加多个音符的频率,用于评测
  1401. };
  1402. // console.log(i,'当前的小节',nodeDetail.MeasureNumberXML,totalMultipleRestMeasures,multipleRestMeasures)
  1403. // 如果是妙极客的曲子,并且第二遍循环播放需要等待时间,并且是第二遍循环的第一个小节的第一个音符
  1404. // if (state.isEvxml && state.secondEvXmlBeginTime && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
  1405. // nodeDetail.time = nodeDetail.time + state.secondEvXmlBeginTime;
  1406. // nodeDetail.endtime = nodeDetail.endtime + state.secondEvXmlBeginTime;
  1407. // usetime = usetime + state.secondEvXmlBeginTime;
  1408. // relativeTime = relativeTime + state.secondEvXmlBeginTime;
  1409. // }
  1410. // if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
  1411. // 如果是和弦音符,需要添加多个音符的频率,用于评测
  1412. if (note.voiceEntry.notes.length > 1) {
  1413. note.voiceEntry.notes.forEach((cnote: any) => {
  1414. if (cnote?.IsChordNote && cnote?.pitch?.frequency) {
  1415. nodeDetail.frequencyList.push(cnote.pitch.frequency)
  1416. }
  1417. })
  1418. }
  1419. const firstRepeatNodeId = allNotes.find((item: any) => item.MeasureNumberXML === state.timegapRepeatMeasureIndex)?.noteId || 0;
  1420. if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === state.timegapRepeatMeasureIndex && nodeDetail.noteId === firstRepeatNodeId) {
  1421. const currentWaitTime = state.evXmlBeginArr[nodeDetail.repeatIdx] || 0;
  1422. nodeDetail.time = nodeDetail.time + currentWaitTime;
  1423. nodeDetail.endtime = nodeDetail.endtime + currentWaitTime;
  1424. usetime = usetime + currentWaitTime;
  1425. relativeTime = relativeTime + currentWaitTime;
  1426. }
  1427. nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
  1428. nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
  1429. let tickables = currenrtVfVoices?.tickables || [];
  1430. if ([121].includes(state.subjectId)) {
  1431. tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
  1432. }
  1433. // console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
  1434. // console.log('👀看看endtime', nodeDetail.duration, relaEndtime, fixtime, i)
  1435. // console.log('音符时间',nodeDetail.i,nodeDetail.time,nodeDetail.endtime)
  1436. tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
  1437. let maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
  1438. // 妙极客的曲子,一个休止小节内可能有多个休止符,此时maxNum是0,需要针对这种情况作处理
  1439. if (note.isRestFlag && maxNum === 0) {
  1440. maxNum = note.maxNoteNum;
  1441. }
  1442. nodeDetail.noteLength = maxNum || 1;
  1443. allNotes.push(nodeDetail);
  1444. allNoteId.push(nodeDetail.id);
  1445. if ( measures.some((item: any) => item.MeasureNumberXML !== nodeDetail.MeasureNumberXML) ) {
  1446. measures = [];
  1447. measures.push(nodeDetail);
  1448. nodeDetail.measures = measures;
  1449. } else {
  1450. measures.push(nodeDetail);
  1451. }
  1452. /**
  1453. * bug: #9877
  1454. * 多分轨合并展示的曲子,不同分轨,同一小节音符的数量可能不能,不能只通过tickables的长度判断该小节的音符数量
  1455. */
  1456. if (si < maxNum - 1) {
  1457. si++;
  1458. } else {
  1459. si = 0;
  1460. relaMeasureLength = 0;
  1461. measures = [];
  1462. }
  1463. preNoteEndTime = nodeDetail.endtime;
  1464. }
  1465. preNoteMeasureNumber = note?.sourceMeasure?.MeasureNumberXML;
  1466. i++;
  1467. }
  1468. // 按照时间轴排序
  1469. const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => Object.assign(item,{i:index}));
  1470. // const sortArray = allNotes.sort((a, b) => a.time - b.time).map((item, index) => ({ ...item, i: index }));
  1471. // const sortArray = allNotes.map((item, index) => ({ ...item, i: index }));
  1472. // 给 xmlNoteTime 和 xmlNoteEndTime 赋值
  1473. let xmlNoteTime = 0
  1474. sortArray.map(item => {
  1475. const noteLengthTime = item.noteLengthTime
  1476. item.xmlNoteTime = retain(xmlNoteTime)
  1477. item.xmlNoteEndTime = retain(xmlNoteTime + noteLengthTime)
  1478. xmlNoteTime += noteLengthTime
  1479. })
  1480. console.timeEnd("音符跑完时间");
  1481. try {
  1482. osmd.cursor.reset();
  1483. } catch (error) {}
  1484. return sortArray;
  1485. };
  1486. /** 获取小节之间的连音线,仅同音高*/
  1487. export const getNoteByMeasuresSlursStart = (note: any) => {
  1488. let activeNote = note;
  1489. let tieNote;
  1490. if (note.noteElement.tie && note.noteElement.tie.StartNote) {
  1491. tieNote = note.noteElement.tie.StartNote;
  1492. }
  1493. if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
  1494. const arr: any = []
  1495. for (const note of state.times) {
  1496. if (tieNote === note.noteElement) {
  1497. arr.push(note)
  1498. }
  1499. }
  1500. if (arr.length) {
  1501. return arr.find((n: any) => n.i === (note.i - 1)) || arr[0]
  1502. }
  1503. }
  1504. return activeNote;
  1505. };
  1506. // 解析xml,获取作词、作曲家名称
  1507. const getComposer = (xmlParse: any) => {
  1508. const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
  1509. for (const creator of creators) {
  1510. if (creator && creator.getAttribute('type') === 'composer' && !state.musicComposer) {
  1511. state.musicComposer = creator.textContent?.trim() || '';
  1512. }
  1513. if (creator && creator.getAttribute('type') === 'lyricist' && !state.musicLyricist) {
  1514. state.musicLyricist = creator.textContent?.trim() || '';
  1515. }
  1516. }
  1517. }
  1518. // 通过xml信息获取重播的小节信息
  1519. const parseXmlToRepeat = (repeats: any) => {
  1520. if (!repeats.length) return
  1521. let repeatInfo: any = []
  1522. // 重复开始小节,结束小节
  1523. let start = 0, end = 0
  1524. for (let i = 0; i < repeats.length; i++) {
  1525. const element = repeats[i];
  1526. const direction = element.getAttribute('direction')
  1527. let parentElement = element.parentNode
  1528. while (parentElement && parentElement.tagName !== 'measure') {
  1529. parentElement = parentElement.parentNode
  1530. }
  1531. let notesNumber = parentElement.getAttribute('number') // 第多少小节,从1开始
  1532. notesNumber = notesNumber ? Number(notesNumber) : 0
  1533. if (direction === 'forward') {
  1534. start = notesNumber
  1535. } else if (direction === 'backward') {
  1536. end = notesNumber
  1537. repeatInfo.push({
  1538. start,
  1539. end
  1540. })
  1541. }
  1542. }
  1543. state.repeatInfo = repeatInfo
  1544. // console.log('重播',repeatInfo)
  1545. }
  1546. // 校验当前选段是否满足重播条件
  1547. export const verifyCanRepeat = (startNum: number, endNum: number) => {
  1548. let repeatIdx = -1
  1549. if (state.repeatInfo.length) {
  1550. for (let i = state.repeatInfo.length - 1; i >= 0; i--) {
  1551. const { start, end } = state.repeatInfo[i];
  1552. if (startNum <= start && endNum >= end) {
  1553. repeatIdx = i
  1554. return {
  1555. repeatIdx,
  1556. canRepeat: true
  1557. }
  1558. break;
  1559. }
  1560. }
  1561. return {
  1562. repeatIdx,
  1563. canRepeat: false
  1564. }
  1565. } else {
  1566. return {
  1567. repeatIdx,
  1568. canRepeat: false
  1569. }
  1570. }
  1571. }
  1572. // 处理妙极客xml谱面
  1573. const customizationXml = (xmlParse: any) => {
  1574. const credits: any = Array.from(xmlParse.querySelectorAll('credit'));
  1575. const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
  1576. const graces: any = Array.from(xmlParse.querySelectorAll('grace'));
  1577. const measures: any[] = Array.from(xmlParse.getElementsByTagName("measure"));
  1578. const notes: any[] = Array.from(xmlParse.getElementsByTagName("note"));
  1579. // 获取音符最多的歌词数,time最多的次数,取两者的最大值,用于自定义循环播放次数
  1580. let maxLyricNum = 0, maxTimeNum = 0;
  1581. if (notes && notes.length) {
  1582. for (const note of notes) {
  1583. if (maxLyricNum < note.getElementsByTagName("lyric").length) {
  1584. maxLyricNum = note.getElementsByTagName("lyric").length
  1585. }
  1586. if (maxTimeNum < note.getElementsByTagName("time").length) {
  1587. maxTimeNum = note.getElementsByTagName("time").length
  1588. }
  1589. }
  1590. }
  1591. state.maxLyricNum = Math.max(maxLyricNum, maxTimeNum);
  1592. // state.osmd.EngravingRules.DYCustomRepeatCount = maxLyricNum;
  1593. ;(window as any).DYCustomRepeatCount = state.maxLyricNum;
  1594. console.log('歌词次数',maxLyricNum)
  1595. if (credits && credits.length) {
  1596. for (const credit of credits) {
  1597. if (credit.getElementsByTagName("credit-type")?.[0]?.textContent === 'lyricist') {
  1598. const creditWord = credit.getElementsByTagName("credit-words")
  1599. creditWord?.[0].setAttribute('justify', 'right')
  1600. }
  1601. }
  1602. }
  1603. if (creators && creators.length) {
  1604. for (const creator of creators) {
  1605. if (creator.getAttribute('type') === 'lyricist') {
  1606. // creator.textContent = '测试一下1';
  1607. }
  1608. }
  1609. }
  1610. // 妙极客xml的倚音(grace)标签需要加上slash=yes属性
  1611. if (graces && graces.length) {
  1612. for (const grace of graces) {
  1613. grace?.setAttribute('slash','yes');
  1614. // console.log(grace,'倚音')
  1615. }
  1616. }
  1617. // 妙极客xml部分小节没有音符,只有Segno,该小节不需要渲染,表示的是反复标记
  1618. for (const measure of measures) {
  1619. const hasNote = measure.getElementsByTagName("note").length;
  1620. const hasSegno = measure.getElementsByTagName("segno").length;
  1621. const sounds = Array.from(measure.getElementsByTagName("sound"));
  1622. const hasSoundSegno = sounds.some((item: any) => item.getAttribute('segno') === 'segno' );
  1623. if (!hasNote && hasSegno && hasSoundSegno) {
  1624. const parent = measure.parentNode;
  1625. parent.removeChild(measure);
  1626. }
  1627. }
  1628. /**
  1629. * bug: #10289,曲目:1782672015612725196、1788040971888537602
  1630. * 妙极客xml,多遍歌词循环的曲目,如果没有repeat标签,需要加上repeat标签
  1631. * */
  1632. if (maxLyricNum > 1) {
  1633. const hasRepeat = xmlParse.querySelectorAll('repeat').length > 0;
  1634. if (!hasRepeat) {
  1635. const parts = xmlParse.querySelectorAll('score-partwise>part')
  1636. if (parts.length) {
  1637. for (const part of parts) {
  1638. const currentMeasures = part.querySelectorAll('measure').length ? Array.from(part.querySelectorAll('measure')) : [];
  1639. const lastMeasure: any = currentMeasures.last();
  1640. if (lastMeasure?.getElementsByTagName('barline').length) {
  1641. const barlineDom = lastMeasure?.getElementsByTagName('barline')[0]
  1642. barlineDom.innerHTML = barlineDom.innerHTML + `<repeat direction="backward" />`;
  1643. } else {
  1644. lastMeasure.innerHTML = lastMeasure.innerHTML + `
  1645. <barline location="right">
  1646. <bar-style>light-heavy</bar-style>
  1647. <repeat direction="backward" />
  1648. </barline>`
  1649. }
  1650. // console.log(lastMeasure)
  1651. }
  1652. }
  1653. }
  1654. }
  1655. }
  1656. // 计算evxml的起始播放时间
  1657. const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
  1658. // xml拍号数
  1659. const xmlNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('num');
  1660. const denNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('den');
  1661. const xmlNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('num');
  1662. const denNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('den');
  1663. const timeGaps: any = xmlParse.getElementsByTagName("timegap")?.length ? Array.from(xmlParse.getElementsByTagName("timegap")?.[0]?.getElementsByTagName("values")?.[0]?.getElementsByTagName("item")) : [];
  1664. state.xmlHasTimes = !!xmlParse.getElementsByTagName("times")?.length
  1665. // 第一个音符的起始时间
  1666. const firstMeasure = xmlParse.getElementsByTagName("measure")[0];
  1667. if (firstMeasure) {
  1668. const firstNoteBeginTime = firstMeasure.getElementsByTagName("times")[0]?.getElementsByTagName("time")[0]?.getAttribute('begin');
  1669. state.evXmlBeginTime = firstNoteBeginTime ? firstNoteBeginTime / 1000 : xmlNum ? 60 / state.originSpeed * xmlNum * 4/denNum : 0;
  1670. state.secondEvXmlBeginTime = firstNoteBeginTime ? 0 : xmlNum2 ? 60 / state.originSpeed * xmlNum2 * 4/denNum2 : 0;
  1671. const hasTimeGap = state.xmlHasTimeGap = xmlParse.getElementsByTagName("timegap").length > 0;
  1672. const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
  1673. if (timeGaps && timeGaps.length && !firstNoteBeginTime) {
  1674. // 有timegap的曲子,需要找到是从哪一小节开始循环的,默认是从第一节开始循环
  1675. const startRepeat = Array.from(xmlParse.getElementsByTagName("repeat") || []).filter((item: any) => item?.getAttribute('direction') === 'forward')
  1676. const firstRepeat: any = startRepeat?.length ? startRepeat[0] : null;
  1677. if (firstRepeat) {
  1678. let parentElement = firstRepeat?.parentNode
  1679. while (parentElement && parentElement.tagName !== 'measure') {
  1680. parentElement = parentElement.parentNode
  1681. }
  1682. state.timegapRepeatMeasureIndex = parentElement?.getAttribute('number') ? Number(parentElement?.getAttribute('number')) : 1;
  1683. }
  1684. for (const timeGap of timeGaps) {
  1685. const num: any = timeGap?.getAttribute('num'), den: any = timeGap?.getAttribute('den');
  1686. const startTime = num ? 60 / state.originSpeed * num * 4/den : 0;
  1687. state.evXmlBeginArr.push(startTime)
  1688. }
  1689. }
  1690. console.log('🚀 ~ evxml解析','有timegap:',hasTimeGap,'有times:',hasTimes,'timegap集合',state.evXmlBeginArr,'第一个timegap',state.evXmlBeginTime)
  1691. }
  1692. // if (!hasTimeGap && !hasTimes) {
  1693. // state.noTimes.push(xmlUrl)
  1694. // }
  1695. }
  1696. /**
  1697. * 兼容处理xml声部移调
  1698. * 打谱软件可能会自动处理移调,这类型的xml就不用通过程序移调了
  1699. * 没有通过软件处理的移调xml,才需要通过程序处理
  1700. * 判读规则:只处理独奏的,不处理合奏的,
  1701. * <instrument-name></instrument-name>标签的值为:Tenor Recorder(竖笛)、Panpipes(排箫)、Ocarina(陶笛)、Woodwind(葫芦丝)、空的和solo,需要程序处理移调
  1702. */
  1703. export const compatibleXmlPitchVoice = (xmlParse: any) => {
  1704. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1705. const partListNames = partNames.filter((item: any) => item?.textContent?.trim().toLocaleUpperCase() !== "COMMON");
  1706. if (partListNames.length == 1) {
  1707. const instrumentNames = Array.from(xmlParse.getElementsByTagName('instrument-name')) || [];
  1708. // @ts-ignore
  1709. const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
  1710. // console.log('instrument名称',instrumentName)
  1711. // 是否需要程序处理移调
  1712. let xmlNeedAdjustVoice = false;
  1713. switch (state.musicalCodeId) {
  1714. case 37:
  1715. case 38:
  1716. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('tenor recorder') ? true : false
  1717. break;
  1718. case 33:
  1719. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('panpipes') ? true : false
  1720. break;
  1721. case 34:
  1722. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('ocarina') ? true : false
  1723. break;
  1724. case 35:
  1725. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('woodwind') ? true : false
  1726. break;
  1727. case 39:
  1728. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('whistling') ? true : false
  1729. break;
  1730. default:
  1731. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') ? true : false
  1732. break;
  1733. }
  1734. // (window as any).xmlNeedAdjustVoice = xmlNeedAdjustVoice
  1735. // 管乐迷的曲子不需要上述判断,修改为都需要程序处理(保持和之前逻辑一致)
  1736. (window as any).xmlNeedAdjustVoice = true
  1737. }
  1738. }
  1739. // 筛选出这个音符中的值(比前一个音符时值大的值)
  1740. function fliterNotesTime(note:any, preTime:number):undefined|number {
  1741. // 音符可能涉及多遍歌词,所以这里要找到对应的times
  1742. if(note?.noteTimeInfo?.length){
  1743. const timeObj = note?.noteTimeInfo.find((value:any) => {
  1744. const beginTime = value?.begin*1000 || 0
  1745. return beginTime > preTime || Math.abs(beginTime - preTime)< 10 //差值在10毫秒之内
  1746. })
  1747. return timeObj?.begin*1000
  1748. }else{
  1749. return undefined
  1750. }
  1751. }