formateMusic.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. import dayjs from "dayjs";
  2. import duration from "dayjs/plugin/duration";
  3. import state from "../state";
  4. import { browser } from "../utils/index";
  5. import { isSpecialMark, isSpeedKeyword, Fraction, SourceMeasure, isGradientWords, GRADIENT_SPEED_RESET_TAG, StringUtil, OpenSheetMusicDisplay } from "/osmd-extended/src";
  6. import { GradualChange, speedInfo } from "./calcSpeed";
  7. const browserInfo = browser();
  8. dayjs.extend(duration);
  9. /**
  10. * 获取节拍器的时间
  11. * @param speed 速度
  12. * @param firstMeasure 曲谱第一个小节
  13. * @returns 节拍器的时间
  14. */
  15. export const getFixTime = (speed: number) => {
  16. const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
  17. let numerator = duration.numerator || 0;
  18. let denominator = duration.denominator || 4;
  19. const beatUnit = duration.beatUnit || "quarter";
  20. // if (state.repeatedBeats) {
  21. // // 音频制作问题仅2拍不重复
  22. // numerator = numerator === 2 ? 4 : numerator;
  23. // }
  24. // console.log('state.isOpenMetronome', state.isOpenMetronome)
  25. return state.isOpenMetronome ? (60 / speed) * formatBeatUnit(beatUnit) * (numerator / denominator) : 0;
  26. };
  27. export const retain = (time: number) => {
  28. return Math.ceil(time * 1000000) / 1000000;
  29. };
  30. export const formatLyricsEntries = (note: any) => {
  31. const voiceEntries = note.parentStaffEntry?.voiceEntries || [];
  32. const lyricsEntries: string[] = [];
  33. for (const voic of voiceEntries) {
  34. if (voic.lyricsEntries?.table) {
  35. const values: any[] = Object.values(voic.lyricsEntries.table);
  36. for (const lyric of values) {
  37. lyricsEntries.push(lyric?.value.text);
  38. }
  39. }
  40. }
  41. return lyricsEntries;
  42. };
  43. export const getMeasureDurationDiff = (measure: any) => {
  44. const { realValue: SRealValue } = measure.activeTimeSignature;
  45. const { realValue: RRealValue } = measure.duration;
  46. return SRealValue - RRealValue;
  47. };
  48. /** 按照dorico的渐快渐慢生成对应的速度 */
  49. export const createSpeedInfo = (gradualChange: GradualChange | undefined, speed: number) => {
  50. if (gradualChange && speedInfo[gradualChange.startWord?.toLocaleLowerCase()]) {
  51. const notenum = Math.max(gradualChange.endXmlNoteIndex, 3);
  52. const speeds: number[] = [];
  53. const startSpeed = speed;
  54. const endSpeed = speed / speedInfo[gradualChange.startWord?.toLocaleLowerCase()];
  55. for (let index = 0; index < notenum; index++) {
  56. const speed = startSpeed + ((endSpeed - startSpeed) / notenum) * (index + 1);
  57. speeds.push(speed);
  58. }
  59. return speeds;
  60. }
  61. return;
  62. };
  63. const tranTime = (str: string = "") => {
  64. let result = str;
  65. const splits = str.split(":");
  66. if (splits.length === 1) {
  67. result = `00:${splits[0]}:00`;
  68. } else if (splits.length === 2) {
  69. result = `00:${splits[0]}:${splits[1]}`;
  70. }
  71. // console.log(`1970-01-01 00:${result}0`)
  72. return `1970-01-01 00:${result}0`;
  73. };
  74. export const getSlursNote = (note: any, pos?: "start" | "end") => {
  75. return pos === "end" ? note.noteElement.slurs[0]?.endNote : note.noteElement.slurs[0]?.startNote;
  76. };
  77. export const getNoteBySlursStart = (note: any, anyNoteHasSlurs?: boolean, pos?: "start" | "end") => {
  78. let activeNote = note;
  79. let slursNote = getSlursNote(activeNote, pos);
  80. for (const item of activeNote.measures) {
  81. if (item.noteElement.slurs.length) {
  82. slursNote = getSlursNote(item, pos);
  83. activeNote = item;
  84. }
  85. }
  86. return activeNote;
  87. };
  88. /** 根据 noteElement 获取note */
  89. export const getParentNote = (note: any) => {
  90. let parentNote;
  91. if (note) {
  92. // time = activeNote.time
  93. for (const n of state.times) {
  94. if (note === n.noteElement) {
  95. // console.log(note)
  96. return n;
  97. }
  98. }
  99. }
  100. return parentNote;
  101. };
  102. export type FractionDefault = {
  103. numerator: number;
  104. denominator: number;
  105. wholeValue: number;
  106. };
  107. export type Duration = FractionDefault & {
  108. TempoInBPM: number;
  109. beatUnit: string;
  110. };
  111. export const getDuration = (osmd?: OpenSheetMusicDisplay): Duration => {
  112. if (osmd) {
  113. const { Duration, TempoInBPM, ActiveTimeSignature, TempoExpressions } = osmd.GraphicSheet.MeasureList[0][0]?.parentSourceMeasure;
  114. if (Duration) {
  115. let beatUnit = "quarter";
  116. for (const item of TempoExpressions) {
  117. beatUnit = item.InstantaneousTempo.beatUnit || "quarter";
  118. }
  119. const duration = formatDuration(ActiveTimeSignature, Duration) as unknown as FractionDefault;
  120. return {
  121. ...duration,
  122. TempoInBPM,
  123. beatUnit,
  124. };
  125. }
  126. }
  127. const duration = new Fraction() as unknown as FractionDefault;
  128. return {
  129. ...duration,
  130. TempoInBPM: 90,
  131. beatUnit: "quarter",
  132. };
  133. };
  134. export function formatDuration(activeTimeSignature: Fraction, duration: Fraction): Fraction {
  135. // 弱起第一小节duration不对
  136. return activeTimeSignature;
  137. }
  138. export function formatBeatUnit(beatUnit: string) {
  139. let multiple = 4;
  140. switch (beatUnit) {
  141. case "1024th":
  142. // bpm = bpm;
  143. multiple = 1024;
  144. break;
  145. case "512th":
  146. // divisionsFromNote = (noteDuration / 4) * 512;
  147. multiple = 512;
  148. break;
  149. case "256th":
  150. // divisionsFromNote = (noteDuration / 4) * 256;
  151. multiple = 256;
  152. break;
  153. case "128th":
  154. // divisionsFromNote = (noteDuration / 4) * 128;
  155. multiple = 128;
  156. break;
  157. case "64th":
  158. // divisionsFromNote = (noteDuration / 4) * 64;
  159. multiple = 64;
  160. break;
  161. case "32nd":
  162. // divisionsFromNote = (noteDuration / 4) * 32;
  163. multiple = 32;
  164. break;
  165. case "16th":
  166. // divisionsFromNote = (noteDuration / 4) * 16;
  167. multiple = 16;
  168. break;
  169. case "eighth":
  170. // divisionsFromNote = (noteDuration / 4) * 8;
  171. multiple = 8;
  172. break;
  173. case "quarter":
  174. multiple = 4;
  175. break;
  176. case "half":
  177. // divisionsFromNote = (noteDuration / 4) * 2;
  178. multiple = 2;
  179. break;
  180. case "whole":
  181. // divisionsFromNote = (noteDuration / 4);
  182. multiple = 1;
  183. break;
  184. case "breve":
  185. // divisionsFromNote = (noteDuration / 4) / 2;
  186. multiple = 0.5;
  187. break;
  188. case "long":
  189. // divisionsFromNote = (noteDuration / 4) / 4;
  190. multiple = 0.25;
  191. break;
  192. case "maxima":
  193. // divisionsFromNote = (noteDuration / 4) / 8;
  194. multiple = 0.125;
  195. break;
  196. default:
  197. break;
  198. }
  199. return multiple;
  200. }
  201. /** 根据音符单位,速度,几几拍计算正确的时间 */
  202. export function getTimeByBeatUnit(beatUnit: string, bpm: number, denominator: number) {
  203. return (denominator / formatBeatUnit(beatUnit)) * bpm;
  204. }
  205. export type CustomInfo = {
  206. showSpeed: boolean;
  207. parsedXML: string;
  208. };
  209. /** 从xml中获取自定义信息,并删除多余的字符串 */
  210. export const getCustomInfo = (xml: string): CustomInfo => {
  211. const data = {
  212. showSpeed: true,
  213. parsedXML: xml,
  214. };
  215. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  216. const words: any = xmlParse.getElementsByTagName("words");
  217. for (const word of words) {
  218. if (word && word.textContent?.trim() === "隐藏速度") {
  219. data.showSpeed = false;
  220. word.textContent = "";
  221. }
  222. if (word && word.textContent?.trim() === "@") {
  223. word.textContent = "segno";
  224. }
  225. }
  226. data.parsedXML = new XMLSerializer().serializeToString(xmlParse);
  227. return data;
  228. };
  229. /**
  230. * 替换文本标签中的内容
  231. */
  232. const replaceTextConent = (beforeText: string, afterText: string, ele: Element): Element => {
  233. const words: any = ele?.getElementsByTagName("words");
  234. for (const word of words) {
  235. if (word && word.textContent?.trim() === beforeText) {
  236. word.textContent = afterText;
  237. }
  238. }
  239. return ele;
  240. };
  241. /**
  242. * 添加第一分谱信息至当前分谱
  243. * @param ele 需要插入的元素
  244. * @param fitstParent 合奏谱第一个分谱
  245. * @param parent 需要添加的分谱
  246. */
  247. const setElementNoteBefore = (ele: Element, fitstParent: Element, parent?: Element | null) => {
  248. let noteIndex: number = 0;
  249. if (!fitstParent) {
  250. return;
  251. }
  252. for (let index = 0; index < fitstParent.childNodes.length; index++) {
  253. const element = fitstParent.childNodes[index];
  254. if (element.nodeName === "note") {
  255. noteIndex++;
  256. }
  257. if (element === ele) {
  258. break;
  259. }
  260. }
  261. if (noteIndex === 0 && parent) {
  262. parent.insertBefore(ele, parent.childNodes[0]);
  263. return;
  264. }
  265. if (parent && parent.childNodes.length > 0) {
  266. let noteIndex2: number = 0;
  267. const notes = Array.from(parent.childNodes).filter((child) => child.nodeName === "note");
  268. const lastNote = notes[notes.length - 1];
  269. if (noteIndex >= notes.length && lastNote) {
  270. parent.insertBefore(ele, parent.childNodes[Array.from(parent.childNodes).indexOf(lastNote)]);
  271. return;
  272. }
  273. for (let index = 0; index < notes.length; index++) {
  274. const element = notes[index];
  275. if (element.nodeName === "note") {
  276. noteIndex2 = noteIndex2 + 1;
  277. if (noteIndex2 === noteIndex) {
  278. parent.insertBefore(ele, element);
  279. break;
  280. }
  281. }
  282. }
  283. }
  284. // console.log(noteIndex, parent)
  285. };
  286. /**
  287. * 检查传入文字是否为重复关键词
  288. * @param text 总谱xml
  289. * @returns 是否是重复关键词
  290. */
  291. export const isRepeatWord = (text: string): boolean => {
  292. if (text) {
  293. const innerText = text.toLocaleLowerCase();
  294. const dsRegEx: string = "d\\s?\\.s\\.";
  295. const dcRegEx: string = "d\\.\\s?c\\.";
  296. return innerText === "@" || StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al fine", true) || StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al coda", true) || StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al fine", true) || StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al coda", true) || StringUtil.StringContainsSeparatedWord(innerText, dcRegEx) || StringUtil.StringContainsSeparatedWord(innerText, "da\\s?capo", true) || StringUtil.StringContainsSeparatedWord(innerText, dsRegEx, true) || StringUtil.StringContainsSeparatedWord(innerText, "dal\\s?segno", true) || StringUtil.StringContainsSeparatedWord(innerText, "al\\s?coda", true) || StringUtil.StringContainsSeparatedWord(innerText, "to\\s?coda", true) || StringUtil.StringContainsSeparatedWord(innerText, "a (la )?coda", true) || StringUtil.StringContainsSeparatedWord(innerText, "fine", true) || StringUtil.StringContainsSeparatedWord(innerText, "coda", true) || StringUtil.StringContainsSeparatedWord(innerText, "segno", true);
  297. }
  298. return false;
  299. };
  300. export const onlyVisible = (xml: string, partIndex: number): string => {
  301. if (!xml) return "";
  302. const detailId = state.examSongId;
  303. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  304. const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
  305. const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0].textContent || "");
  306. const parts: any = xmlParse.getElementsByTagName("part");
  307. // const firstTimeInfo = parts[0]?.getElementsByTagName('metronome')[0]?.parentElement?.parentElement?.cloneNode(true)
  308. const firstMeasures = [...parts[0]?.getElementsByTagName("measure")];
  309. const metronomes = [...parts[0]?.getElementsByTagName("metronome")];
  310. const words = [...parts[0]?.getElementsByTagName("words")];
  311. const codas = [...parts[0]?.getElementsByTagName("coda")];
  312. const rehearsals = [...parts[0]?.getElementsByTagName("rehearsal")];
  313. /** 第一分谱如果是约定的配置分谱则跳过 */
  314. if (partListNames[0]?.toLocaleUpperCase?.() === "COMMON") {
  315. partIndex++;
  316. partListNames.shift();
  317. }
  318. const visiblePartInfo = partList[partIndex];
  319. // console.log(visiblePartInfo, partIndex)
  320. state.partListNames = partListNames;
  321. if (visiblePartInfo) {
  322. const id = visiblePartInfo.getAttribute("id");
  323. Array.from(parts).forEach((part: any) => {
  324. if (part && part.getAttribute("id") !== id) {
  325. part.parentNode?.removeChild(part);
  326. // 不等于第一行才添加避免重复添加
  327. } else if (part && part.getAttribute("id") !== "P1") {
  328. // 速度标记仅保留最后一个
  329. const metronomeData: {
  330. [key in string]: Element;
  331. } = {};
  332. for (let i = 0; i < metronomes.length; i++) {
  333. const metronome = metronomes[i];
  334. const metronomeContainer = metronome.parentElement?.parentElement?.parentElement;
  335. if (metronomeContainer) {
  336. const index = firstMeasures.indexOf(metronomeContainer);
  337. metronomeData[index] = metronome;
  338. }
  339. }
  340. Object.values(metronomeData).forEach((metronome) => {
  341. const metronomeContainer: any = metronome.parentElement?.parentElement;
  342. const parentMeasure: any = metronomeContainer?.parentElement;
  343. const measureMetronomes = [...(parentMeasure?.childNodes || [])];
  344. const metronomesIndex = metronomeContainer ? measureMetronomes.indexOf(metronomeContainer) : -1;
  345. // console.log(parentMeasure)
  346. if (parentMeasure && metronomesIndex > -1) {
  347. const index = firstMeasures.indexOf(parentMeasure);
  348. const activeMeasure = part.getElementsByTagName("measure")[index];
  349. setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
  350. }
  351. });
  352. /** word比较特殊需要精确到note位置 */
  353. words.forEach((word) => {
  354. let text = word.textContent || "";
  355. text = ["cresc."].includes(text) ? "" : text;
  356. if ((isSpecialMark(text) || isSpeedKeyword(text) || isGradientWords(text) || isRepeatWord(text) || GRADIENT_SPEED_RESET_TAG) && text) {
  357. const wordContainer = word.parentElement?.parentElement;
  358. const parentMeasure = wordContainer?.parentElement;
  359. const measureWords = [...(parentMeasure?.childNodes || [])];
  360. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  361. if (wordContainer && parentMeasure && wordIndex > -1) {
  362. const index = firstMeasures.indexOf(parentMeasure);
  363. const activeMeasure = part.getElementsByTagName("measure")[index];
  364. // 找当前小节是否包含word标签
  365. const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
  366. // 遍历word标签,检查是否和第一小节重复,如果有重复则不平移word
  367. const total = _words.reduce((total: any, _word: any) => {
  368. if (_word.textContent?.includes(text)) {
  369. total++;
  370. }
  371. return total;
  372. }, 0);
  373. if (total === 0) {
  374. if (["12280"].includes(detailId)) {
  375. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  376. } else {
  377. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  378. }
  379. }
  380. }
  381. }
  382. });
  383. /** word比较特殊需要精确到note位置 */
  384. codas.forEach((coda) => {
  385. const wordContainer = coda.parentElement?.parentElement;
  386. const parentMeasure = wordContainer?.parentElement;
  387. const measureWords = [...(parentMeasure?.childNodes || [])];
  388. const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
  389. if (wordContainer && parentMeasure && wordIndex > -1) {
  390. const index = firstMeasures.indexOf(parentMeasure);
  391. const activeMeasure = part.getElementsByTagName("measure")[index];
  392. if (["12280"].includes(detailId)) {
  393. activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
  394. } else {
  395. setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
  396. }
  397. }
  398. });
  399. rehearsals.forEach((rehearsal) => {
  400. const container = rehearsal.parentElement?.parentElement;
  401. const parentMeasure = container?.parentElement;
  402. // console.log(rehearsal)
  403. if (parentMeasure) {
  404. const index = firstMeasures.indexOf(parentMeasure);
  405. part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
  406. // console.log(index, parentMeasure, firstMeasures.indexOf(parentMeasure))
  407. }
  408. });
  409. } else {
  410. words.forEach((word) => {
  411. const text = word.textContent || "";
  412. if (isSpeedKeyword(text) && text) {
  413. const wordContainer = word.parentElement?.parentElement?.parentElement;
  414. if (wordContainer && wordContainer.firstElementChild && wordContainer.firstElementChild !== word) {
  415. const wordParent = word.parentElement?.parentElement;
  416. const fisrt = wordContainer.firstElementChild;
  417. wordContainer.insertBefore(wordParent, fisrt);
  418. }
  419. }
  420. });
  421. }
  422. // 最后一个小节的结束线元素不在最后 调整
  423. if (part && part.getAttribute("id") === id) {
  424. const barlines = part.getElementsByTagName("barline");
  425. const lastParent = barlines[barlines.length - 1]?.parentElement;
  426. if (lastParent?.lastElementChild?.tagName !== "barline") {
  427. const children = lastParent?.children || [];
  428. for (let el of children) {
  429. if (el.tagName === "barline") {
  430. // 将结束线元素放到最后
  431. lastParent?.appendChild(el);
  432. break;
  433. }
  434. }
  435. }
  436. }
  437. });
  438. Array.from(partList).forEach((part) => {
  439. if (part && part.getAttribute("id") !== id) {
  440. part.parentNode?.removeChild(part);
  441. }
  442. });
  443. }
  444. // console.log(xmlParse)
  445. return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
  446. };
  447. // 倚音后连音线
  448. export const appoggianceFormate = (xmlParse: Document): Document => {
  449. if (!xmlParse) return xmlParse;
  450. const graces: any = xmlParse.querySelectorAll("grace");
  451. if (!graces.length) return xmlParse;
  452. const getNextElement = (el: HTMLElement): HTMLElement => {
  453. if (el.querySelector("grace")) {
  454. return getNextElement(el?.nextElementSibling as HTMLElement);
  455. }
  456. return el;
  457. };
  458. for (let grace of graces) {
  459. const notations = grace.parentElement?.querySelector("notations");
  460. if (notations && notations.querySelectorAll("slur").length > 1) {
  461. let nextEle: Element = getNextElement(grace.parentElement?.nextElementSibling as HTMLElement);
  462. if (nextEle && nextEle.querySelectorAll("slur").length > 0) {
  463. const slurNumber = Array.from(nextEle.querySelector("notations")?.children || []).map((el: Element) => {
  464. return el.getAttribute("number");
  465. });
  466. const slurs = notations.querySelectorAll("slur");
  467. for (let nota of slurs) {
  468. if (!slurNumber.includes(nota.getAttribute("number"))) {
  469. nextEle.querySelector("notations")?.appendChild(nota);
  470. }
  471. }
  472. }
  473. }
  474. }
  475. return xmlParse;
  476. };
  477. /** 根据ID获取最顶级ID */
  478. export const isWithinScope = (tree: any[], id: number): number => {
  479. if (!tree) return 0;
  480. let result = 0;
  481. for (const item of tree) {
  482. if (item.id === id) {
  483. result = item.id;
  484. break;
  485. }
  486. if (item.sysMusicScoreCategoriesList) {
  487. result = isWithinScope(item.sysMusicScoreCategoriesList, id);
  488. if (result > 0) {
  489. result = item.id;
  490. }
  491. if (result) break;
  492. }
  493. }
  494. return result;
  495. };
  496. class NoteList {
  497. notes: any[] = [];
  498. constructor(notes: any[]) {
  499. this.notes = notes;
  500. }
  501. public last() {
  502. return this.notes[this.notes.length - 1];
  503. }
  504. public list() {
  505. return this.notes;
  506. }
  507. }
  508. export const getNotesByid = (id: string): NoteList => {
  509. const notes = new NoteList(state.times.filter((item) => item.id === id));
  510. return notes;
  511. };
  512. /** 格式化当前曲谱缩放比例 */
  513. export const formatZoom = (num = 1) => {
  514. return num * state.zoom;
  515. };
  516. /** 格式化曲谱
  517. * 1.全休止符的小节,没有音符默认加个全休止符
  518. */
  519. export const formatXML = (xml: string): string => {
  520. if (!xml) return "";
  521. const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
  522. const measures = Array.from(xmlParse.getElementsByTagName("measure"));
  523. // let speed = -1
  524. let beats = -1;
  525. let beatType = -1;
  526. // 小节中如果没有节点默认为休止符
  527. for (const measure of measures) {
  528. if (beats === -1 && measure.getElementsByTagName("beats").length) {
  529. beats = parseInt(measure.getElementsByTagName("beats")[0].textContent || "4");
  530. }
  531. if (beatType === -1 && measure.getElementsByTagName("beat-type").length) {
  532. beatType = parseInt(measure.getElementsByTagName("beat-type")[0].textContent || "4");
  533. }
  534. // if (speed === -1 && measure.getElementsByTagName('per-minute').length) {
  535. // speed = parseInt(measure.getElementsByTagName('per-minute')[0].textContent || this.firstLib?.speed)
  536. // }
  537. const divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || "256");
  538. if (measure.getElementsByTagName("note").length === 0) {
  539. const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
  540. if (forwardTimeElement) {
  541. forwardTimeElement.textContent = "0";
  542. }
  543. measure.innerHTML =
  544. measure.innerHTML +
  545. `
  546. <note>
  547. <rest measure="yes"/>
  548. <duration>${divisions * beats}</duration>
  549. <voice>1</voice>
  550. <type>whole</type>
  551. </note>`;
  552. }
  553. }
  554. return new XMLSerializer().serializeToString(xmlParse);
  555. };
  556. /** 获取所有音符的时值,以及格式化音符 */
  557. export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
  558. const detailId = state.examSongId?.toString();
  559. const partIndex = state.partIndex + "";
  560. let fixtime = browserInfo.huawei ? 0.08 : 0; //getFixTime()
  561. const allNotes: any[] = [];
  562. const allNoteId: string[] = [];
  563. const allMeasures: any[] = [];
  564. const { originSpeed: baseSpeed } = state;
  565. const formatRealKey = (realKey: number, detail: any) => {
  566. // 长笛的LEVEL 2-5-1条练习是泛音练习,以每小节第一个音的指法为准,高音不变变指法。
  567. const olnyOneIds = ["906"];
  568. if (olnyOneIds.includes(detailId)) {
  569. return detail.measures[0]?.realKey || realKey;
  570. }
  571. // 圆号的LEVEL 2-5条练习是泛音练习,最后四小节指法以连音线第一个小节为准
  572. const olnyOneIds2 = ["782", "784"];
  573. if (olnyOneIds2.includes(detailId)) {
  574. const measureNumbers = [14, 16, 30, 32];
  575. if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
  576. return allNotes[allNotes.length - 1]?.realKey || realKey;
  577. }
  578. }
  579. // 2-6 第三小节指法按照第一个音符显示
  580. const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
  581. if (filterIds.includes(detailId)) {
  582. if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
  583. return detail.measures[0]?.realKey || realKey;
  584. }
  585. }
  586. return realKey;
  587. };
  588. if (!osmd.cursor) return [];
  589. try {
  590. // osmd.cursor.reset();
  591. } catch (error) {}
  592. const iterator: any = osmd.cursor.Iterator;
  593. // console.log("🚀 ~ iterator:", iterator)
  594. console.time("音符跑完时间");
  595. let i = 0;
  596. let si = 0;
  597. let measures: any[] = [];
  598. let stepSpeeds: number[] = [];
  599. /** 弱起时间 */
  600. let difftime = 0;
  601. let usetime = 0;
  602. let useGradualTime = 0;
  603. let relaMeasureLength = 0;
  604. let beatUnit = "quarter";
  605. let gradualSpeed;
  606. let gradualChange: GradualChange | undefined;
  607. let gradualChangeIndex = 0;
  608. let totalMultipleRestMeasures = 0
  609. let multipleRestMeasures = 0
  610. const _notes = [] as any[];
  611. if (state.gradualTimes) {
  612. // 管乐迷
  613. // if (["12280"].includes(detailId) && ["24"].includes(partIndex)) {
  614. // state.gradualTimes["8"] = "00:25:63";
  615. // state.gradualTimes["66"] = "01:53:35";
  616. // state.gradualTimes["90"] = "02:41:40";
  617. // }
  618. console.log("合奏速度", state.gradual, state.gradualTimes);
  619. }
  620. let currentTimeStamp = iterator.currentTimeStamp.RealValue;
  621. const currentTimes = [] as any[];
  622. let isSetNextNoteReal = false;
  623. let differFrom = 0;
  624. while (!iterator.EndReached) {
  625. // console.log({ ...iterator });
  626. const voiceEntries = iterator.CurrentVoiceEntries?.[0] ? [iterator.CurrentVoiceEntries?.[0]] : [];
  627. let currentVoiceEntries: any[] = [];
  628. // 单声部多声轨
  629. if (state.multitrack > 0) {
  630. currentVoiceEntries = [...iterator.CurrentVoiceEntries];
  631. } else {
  632. currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
  633. return n && n?.ParentVoice?.VoiceId != 1;
  634. });
  635. }
  636. let currentTime = 0;
  637. let isDouble = false;
  638. let isMutileSubject = false;
  639. // console.log(iterator.currentMeasureIndex, [...iterator.currentVoiceEntries])
  640. // iterator.currentMeasureIndex == 45 && console.log(currentTimeStamp, [...iterator.currentVoiceEntries])
  641. if (currentVoiceEntries.length && !isSetNextNoteReal) {
  642. // iterator.currentMeasureIndex == 15 && console.log(iterator.currentMeasureIndex, isSetNextNoteReal)
  643. isDouble = true;
  644. let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
  645. notes.push(...n.Notes);
  646. return notes;
  647. }, [] as any);
  648. voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
  649. currentTime = voiceNotes?.[0]?.length?.realValue || 0;
  650. // iterator.currentMeasureIndex == 15 && console.log("🚀 ~ currentTime:", currentTime)
  651. if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
  652. const min = voiceNotes[0]?.length?.realValue || 0;
  653. const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
  654. differFrom = max - min;
  655. isSetNextNoteReal = differFrom === 0 ? false : true;
  656. // iterator.currentMeasureIndex == 15 && console.log("🚀 ~ differFrom:", differFrom, isSetNextNoteReal)
  657. // console.log(iterator.currentMeasureIndex, min, max)
  658. }
  659. }
  660. // 多声部上下音符没对齐,光标多走一拍
  661. if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
  662. isMutileSubject = true;
  663. }
  664. if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
  665. isDouble = true;
  666. currentTime = differFrom;
  667. isSetNextNoteReal = false;
  668. differFrom = 0;
  669. // iterator.currentMeasureIndex == 7 && console.log("🚀 ~ currentTime:",iterator.currentMeasure, currentTime)
  670. }
  671. currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
  672. currentTimeStamp = iterator.currentTimeStamp.realValue;
  673. for (const v of voiceEntries) {
  674. let note = v.notes[0];
  675. if (note.IsGraceNote){
  676. // 如果是装饰音, 取不是装饰音的时值
  677. const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace)
  678. note = voice.notes[0];
  679. }
  680. note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
  681. // 有倚音
  682. if (note?.voiceEntry?.isGrace) {
  683. isDouble = true;
  684. let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
  685. notes.push(...n.notes);
  686. return notes;
  687. }, []);
  688. ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
  689. currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
  690. }
  691. if (state.multitrack > 0 && currentTime > note.length.realValue) {
  692. // console.log(iterator.currentMeasureIndex, currentTime , note.length.realValue)
  693. currentTime = note.length.realValue;
  694. }
  695. _notes.push({
  696. note,
  697. iterator: { ...iterator },
  698. currentTime,
  699. isDouble,
  700. isMutileSubject,
  701. });
  702. }
  703. iterator.moveToNextVisibleVoiceEntry(false);
  704. }
  705. for (let { note, iterator, currentTime, isDouble, isMutileSubject } of _notes) {
  706. if (note) {
  707. if (si === 0) {
  708. allMeasures.push(note.sourceMeasure);
  709. }
  710. if (si === 0 && state.isSpecialBookCategory) {
  711. for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
  712. if (expression?.InstantaneousTempo?.beatUnit) {
  713. // 取最后一个有效的tempo
  714. // activeInstantaneousTempo = expression.InstantaneousTempo
  715. beatUnit = expression.InstantaneousTempo.beatUnit;
  716. // beatUnit = expression.InstantaneousTempo.beatUnit
  717. }
  718. }
  719. }
  720. let measureSpeed = note.sourceMeasure.tempoInBPM;
  721. const { metronomeNoteIndex } = iterator.currentMeasure;
  722. if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
  723. measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
  724. }
  725. const activeVerticalMeasureList = [note.sourceMeasure.verticalMeasureList?.[0]] || [];
  726. // console.log([...activeVerticalMeasureList])
  727. const { realValue } = iterator.currentTimeStamp;
  728. // console.log({...iterator}, i)
  729. const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(iterator.currentMeasure.activeTimeSignature, iterator.currentMeasure.duration);
  730. let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
  731. // 管乐迷
  732. // if (i === 0 && ["2670"].includes(detailId)) {
  733. // NoteRealValue = 0.03125;
  734. // }
  735. if (isDouble && currentTime > 0) {
  736. if (currentTime != NoteRealValue) {
  737. console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
  738. NoteRealValue = currentTime;
  739. }
  740. }
  741. // note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
  742. // 管乐迷
  743. // if (["12667", "12673"].includes(detailId)) {
  744. // if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
  745. // NoteRealValue = currentTimes[i + 1];
  746. // }
  747. // }
  748. // if (["12673"].includes(detailId) && ["22"].includes(partIndex) && i == 208) {
  749. // console.log(note.sourceMeasure.MeasureNumberXML, i);
  750. // NoteRealValue = 0.125;
  751. // }
  752. let relativeTime = usetime;
  753. // 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度,否则mp3速度不对
  754. let beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  755. // 如果有节拍器,需要将节拍器的时间算出来
  756. if (i === 0) {
  757. fixtime += getFixTime(beatSpeed);
  758. console.log("🚀 ~ fixtime:", fixtime, beatSpeed)
  759. }
  760. // console.log(getTimeByBeatUnit(beatUnit, measureSpeed, iterator.currentMeasure.activeTimeSignature.Denominator))
  761. let gradualLength = 0;
  762. let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  763. gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
  764. gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
  765. if (!gradualSpeed || gradualSpeed.length < 2) {
  766. gradualSpeed = createSpeedInfo(gradualChange, speed);
  767. }
  768. // console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
  769. const measureListIndex = iterator.currentMeasure.measureListIndex;
  770. // 计算相差时间按照比例分配到所有音符上
  771. if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
  772. const withInRangeNote = state.gradual.find((item, index) => {
  773. const nextItem: any = state.gradual[index + 1];
  774. return item[0].measureIndex <= measureListIndex && item[1]?.measureIndex! >= measureListIndex && (!nextItem || nextItem?.[0].measureIndex !== measureListIndex);
  775. });
  776. if (!withInRangeNote) {
  777. useGradualTime = 0;
  778. }
  779. const [first, last] = withInRangeNote || [];
  780. if (first && last) {
  781. // 小节数量
  782. const continuous = last.measureIndex - first.measureIndex;
  783. // 开始小节内
  784. const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
  785. // 结束小节内
  786. const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
  787. // 范围内小节
  788. const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
  789. if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
  790. const startTime = state.gradualTimes[first.measureIndex];
  791. const endTime = state.gradualTimes[last.measureIndex];
  792. if (startTime && endTime) {
  793. const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
  794. const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
  795. gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
  796. useGradualTime += gradualLength;
  797. }
  798. }
  799. }
  800. } else if (state.appName === 'GYM' && gradualChange && gradualSpeed && (gradualChange.startXmlNoteIndex === si || gradualChangeIndex > 0)) {
  801. const startSpeed = gradualSpeed[0] - (gradualSpeed[1] - gradualSpeed[0]);
  802. const { resetXmlNoteIndex, endXmlNoteIndex } = gradualChange;
  803. const noteDiff = endXmlNoteIndex;
  804. let stepSpeed = (gradualSpeed[gradualSpeed.length - 1] - startSpeed) / noteDiff;
  805. stepSpeed = note.DotsXml ? stepSpeed / 1.5 : stepSpeed;
  806. if (gradualChangeIndex < noteDiff) {
  807. const tempSpeed = Math.ceil(speed + stepSpeed * gradualChangeIndex);
  808. let tmpSpeed = getTimeByBeatUnit(beatUnit, tempSpeed, iterator.currentMeasure.activeTimeSignature.Denominator);
  809. const maxLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
  810. // speed += stepSpeeds.reduce((a, b) => a + b, 0)
  811. speed += Math.ceil(stepSpeed * (gradualChangeIndex + 1));
  812. tmpSpeed = getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator);
  813. const minLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
  814. gradualLength = (maxLength + minLength) / 2;
  815. } else if (resetXmlNoteIndex > gradualChangeIndex) {
  816. speed = allNotes[i - 1]?.speed;
  817. }
  818. beatSpeed = (state.isSpecialBookCategory ? getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator) : baseSpeed) || 1;
  819. const isEnd = !(gradualChangeIndex < noteDiff) && !(resetXmlNoteIndex > gradualChangeIndex);
  820. gradualChangeIndex++;
  821. if (isEnd) {
  822. gradualChangeIndex = 0;
  823. gradualChange = undefined;
  824. gradualSpeed = undefined;
  825. stepSpeeds = [];
  826. }
  827. }
  828. const _noteLength = NoteRealValue
  829. let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  830. const measureLength = vRealValue * vDenominator * (60 / beatSpeed);
  831. // console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
  832. // console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
  833. usetime += noteLength;
  834. relaMeasureLength += noteLength;
  835. let relaEndtime = noteLength + relativeTime;
  836. const fixedKey = note.fixedKey || 0;
  837. const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
  838. // console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
  839. if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
  840. continue;
  841. }
  842. // console.log(iterator.currentMeasure)
  843. // 如果是弱起就补齐缺省的时长
  844. if (i === 0) {
  845. const diff = getMeasureDurationDiff(iterator.currentMeasure);
  846. if (diff > 0) {
  847. difftime = diff * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  848. fixtime += difftime;
  849. }
  850. // diff获取不准确时, 弱起补齐
  851. if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
  852. difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  853. fixtime += difftime;
  854. }
  855. }
  856. let stave = activeVerticalMeasureList[0]?.stave
  857. if (!stave && note.isRestFlag && allNotes.length) {
  858. // 全休止符, 公用stave
  859. // stave = allNotes[allNotes.length - 1].stave
  860. }
  861. if(note.sourceMeasure.multipleRestMeasures) {
  862. totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures
  863. multipleRestMeasures = 0
  864. }
  865. if (multipleRestMeasures < totalMultipleRestMeasures) {
  866. multipleRestMeasures++
  867. } else {
  868. multipleRestMeasures = 0
  869. totalMultipleRestMeasures = 0
  870. }
  871. // console.log(note.tie)
  872. const nodeDetail = {
  873. isStaccato: note.voiceEntry.isStaccato(),
  874. isRestFlag: note.isRestFlag,
  875. noteId: note.NoteToGraphicalNoteObjectId,
  876. measureListIndex: note.sourceMeasure.measureListIndex,
  877. MeasureNumberXML: note.sourceMeasure.MeasureNumberXML,
  878. _noteLength: _noteLength,
  879. svgElement: svgElement,
  880. frequency: note?.pitch?.frequency || -1,
  881. nextFrequency: note?.pitch?.nextFrequency || -1,
  882. prevFrequency: note?.pitch?.prevFrequency || -1,
  883. difftime,
  884. octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
  885. speed,
  886. beatSpeed,
  887. i,
  888. si,
  889. stepSpeeds,
  890. measureOpenIndex: allMeasures.length - 1,
  891. measures,
  892. tempoInBPM: note.sourceMeasure.tempoInBPM,
  893. measureLength,
  894. relaMeasureLength,
  895. id: svgElement?.attrs.id,
  896. note: note.halfTone + 12, // see issue #224
  897. relativeTime: retain(relativeTime),
  898. time: retain(relativeTime + fixtime),
  899. endtime: retain(relaEndtime + fixtime),
  900. relaEndtime: retain(relaEndtime),
  901. realValue,
  902. halfTone: note.halfTone,
  903. noteElement: note,
  904. fixedKey,
  905. realKey: 0,
  906. duration: 0,
  907. formatLyricsEntries: formatLyricsEntries(note),
  908. stave,
  909. firstVerticalMeasure: activeVerticalMeasureList[0],
  910. noteLength: 1,
  911. osdmContext: osmd,
  912. speedbeatUnit: beatUnit,
  913. multipleRestMeasures: multipleRestMeasures,
  914. };
  915. nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
  916. nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
  917. let tickables = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables || [];
  918. if ([121].includes(state.subjectId)) {
  919. tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
  920. }
  921. // console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
  922. nodeDetail.noteLength = tickables.length || 1;
  923. allNotes.push(nodeDetail);
  924. allNoteId.push(nodeDetail.id);
  925. measures.push(nodeDetail);
  926. if (si < tickables.length - 1) {
  927. si++;
  928. } else {
  929. si = 0;
  930. relaMeasureLength = 0;
  931. measures = [];
  932. }
  933. }
  934. i++;
  935. }
  936. // 按照时间轴排序
  937. const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => ({ ...item, i: index }));
  938. console.timeEnd("音符跑完时间");
  939. try {
  940. osmd.cursor.reset();
  941. } catch (error) {}
  942. state.activeMeasureIndex = sortArray[0].MeasureNumberXML
  943. return sortArray;
  944. };
  945. /** 获取小节之间的连音线,仅同音高*/
  946. export const getNoteByMeasuresSlursStart = (note: any) => {
  947. let activeNote = note;
  948. let tieNote;
  949. if (note.noteElement.tie && note.noteElement.tie.StartNote) {
  950. tieNote = note.noteElement.tie.StartNote;
  951. }
  952. if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
  953. for (const note of state.times) {
  954. if (tieNote === note.noteElement) {
  955. return note;
  956. }
  957. }
  958. }
  959. return activeNote;
  960. };