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