formateMusic.ts 52 KB

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