formateMusic.ts 73 KB

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