formateMusic.ts 72 KB

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