formateMusic.ts 75 KB

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