formateMusic.ts 70 KB

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