formateMusic.ts 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
  634. if (measure.getElementsByTagName("words").length && state.isEvxml) {
  635. const wordList = Array.from(measure.getElementsByTagName("words")) || [];
  636. wordList.forEach((word: any) => {
  637. // TODO:删除妙极客曲子无意义的words
  638. // wordArr?.push(word?.textContent)
  639. if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
  640. measure.removeChild(word.parentNode.parentNode);
  641. // deleteWordArr?.push(word?.textContent)
  642. }
  643. // if(hideSpeedWords.includes(word?.textContent) && word?.parentNode?.parentNode) {
  644. // measure.removeChild(word.parentNode.parentNode);
  645. // }
  646. })
  647. }
  648. if (measure.getElementsByTagName("note").length === 0) {
  649. const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
  650. if (forwardTimeElement) {
  651. forwardTimeElement.textContent = "0";
  652. }
  653. measure.innerHTML =
  654. measure.innerHTML +
  655. `
  656. <note>
  657. <rest measure="yes"/>
  658. <duration>${divisions * beats}</duration>
  659. <voice>1</voice>
  660. <type>whole</type>
  661. </note>`;
  662. }
  663. }
  664. // 如果曲谱详情接口没有返回速度,则取xml第一小节的速度,如果取不到,则取默认速度:100
  665. if (!speed || speed == -1) {
  666. speed = 100
  667. }
  668. if (!state.originSpeed) {
  669. state.originSpeed = state.speed = speed || 100
  670. }
  671. return new XMLSerializer().serializeToString(xmlParse);
  672. };
  673. /** 获取所有音符的时值,以及格式化音符 */
  674. export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
  675. const customNoteRealValue = customData.customNoteRealValue;
  676. const customNoteCurrentTime = customData.customNoteCurrentTime;
  677. const detailId = state.examSongId + "";
  678. const partIndex = state.partIndex + "";
  679. let fixtime = browserInfo.huawei ? 0.08 : 0; //getFixTime()
  680. const allNotes: any[] = [];
  681. const allNoteId: string[] = [];
  682. const allMeasures: any[] = [];
  683. const { originSpeed: baseSpeed } = state;
  684. let preMeasureNumber = 0;
  685. const formatRealKey = (realKey: number, detail: any) => {
  686. // 不是管乐迷, 不处理
  687. // if (state.appName !== "GYM") return realKey;
  688. // 长笛的LEVEL 2-5-1条练习是泛音练习,以每小节第一个音的指法为准,高音不变变指法。
  689. const olnyOneIds = ["906"];
  690. if (olnyOneIds.includes(state.cbsExamSongId)) {
  691. return detail.measures[0]?.realKey || realKey;
  692. }
  693. // 圆号的LEVEL 2-5条练习是泛音练习,最后四小节指法以连音线第一个小节为准
  694. const olnyOneIds2 = ["782", "784"];
  695. if (olnyOneIds2.includes(state.cbsExamSongId)) {
  696. const measureNumbers = [14, 16, 30, 32];
  697. if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
  698. return allNotes[allNotes.length - 1]?.realKey || realKey;
  699. }
  700. }
  701. // 2-6 第三小节指法按照第一个音符显示
  702. const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
  703. if (filterIds.includes(state.cbsExamSongId)) {
  704. if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
  705. return detail.measures[0]?.realKey || realKey;
  706. }
  707. }
  708. return realKey;
  709. };
  710. if (!osmd.cursor) return [];
  711. const iterator: any = osmd.cursor.Iterator;
  712. // console.log("🚀 ~ iterator:", iterator)
  713. console.time("音符跑完时间");
  714. let i = 0;
  715. let si = 0;
  716. let measures: any[] = [];
  717. let stepSpeeds: number[] = [];
  718. /** 弱起时间 */
  719. let difftime = 0;
  720. let usetime = 0;
  721. let relaMeasureLength = 0;
  722. let beatUnit = "quarter";
  723. let gradualSpeed;
  724. let gradualChange: GradualChange | undefined;
  725. let gradualChangeIndex = 0;
  726. let totalMultipleRestMeasures = 0;
  727. let multipleRestMeasures = 0;
  728. let staveNoteIndex = 0;
  729. let staveIndex = 0;
  730. const _notes = [] as any[];
  731. if (state.gradualTimes) {
  732. console.log("后台设置的渐慢小节时间", state.gradual, state.gradualTimes);
  733. }
  734. let currentTimeStamp = iterator.currentTimeStamp.RealValue;
  735. const currentTimes = [] as any[];
  736. let isSetNextNoteReal = false;
  737. let differFrom = 0;
  738. while (!iterator.EndReached) {
  739. // console.log({ ...iterator });
  740. const voiceEntries = iterator.CurrentVoiceEntries?.[0] ? [iterator.CurrentVoiceEntries?.[0]] : [];
  741. let currentVoiceEntries: any[] = [];
  742. // 多分轨,当前小节最大音符数量
  743. let maxNoteNum = 0;
  744. // iterator.currentMeasure?.verticalMeasureList?.forEach((item: any) => maxNoteNum = Math.max(maxNoteNum, item?.staffEntries?.length || 0))
  745. maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
  746. // console.log(iterator.currentMeasure.MeasureNumberXML,maxNoteNum,iterator.currentMeasure?.verticalSourceStaffEntryContainers.length)
  747. // 单声部多声轨
  748. if (state.multitrack > 0) {
  749. currentVoiceEntries = [...iterator.CurrentVoiceEntries];
  750. } else {
  751. currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
  752. return n && n?.ParentVoice?.VoiceId != 1;
  753. });
  754. }
  755. let currentTime = 0;
  756. let isDouble = false;
  757. let isMutileSubject = false;
  758. if (currentVoiceEntries.length && !isSetNextNoteReal) {
  759. isDouble = true;
  760. let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
  761. notes.push(...n.Notes);
  762. return notes;
  763. }, [] as any);
  764. voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
  765. currentTime = voiceNotes?.[0]?.length?.realValue || 0;
  766. if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
  767. const min = voiceNotes[0]?.length?.realValue || 0;
  768. const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
  769. differFrom = max - min;
  770. isSetNextNoteReal = differFrom === 0 ? false : true;
  771. }
  772. }
  773. // 多声部上下音符没对齐,光标多走一拍
  774. if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
  775. isMutileSubject = true;
  776. }
  777. if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
  778. isDouble = true;
  779. currentTime = differFrom;
  780. isSetNextNoteReal = false;
  781. differFrom = 0;
  782. }
  783. currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
  784. currentTimeStamp = iterator.currentTimeStamp.realValue;
  785. for (const v of voiceEntries) {
  786. let note = v.notes[0];
  787. if (note.IsGraceNote) {
  788. // 如果是装饰音, 取不是装饰音的时值
  789. const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace);
  790. note = voice.notes[0];
  791. }
  792. note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
  793. // 有倚音
  794. if (note?.voiceEntry?.isGrace) {
  795. isDouble = true;
  796. let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
  797. notes.push(...n.notes);
  798. return notes;
  799. }, []);
  800. ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
  801. currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
  802. }
  803. if (state.multitrack > 0 && currentTime > note.length.realValue) {
  804. currentTime = note.length.realValue;
  805. }
  806. note.maxNoteNum = maxNoteNum
  807. _notes.push({
  808. note,
  809. iterator: { ...iterator },
  810. currentTime,
  811. isDouble,
  812. isMutileSubject,
  813. measuresTempoInBPM: note?.sourceMeasure?.tempoInBPM
  814. });
  815. }
  816. iterator.moveToNextVisibleVoiceEntry(false);
  817. }
  818. // 是否是变速的曲子
  819. const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
  820. console.log('变速曲子',hasVaryingSpeed, _notes)
  821. let noteIds: any = [];
  822. // let voicesBBox: any = null;
  823. for (let { note, iterator, currentTime, isDouble, isMutileSubject } of _notes) {
  824. if (note) {
  825. if (preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  826. si = 0
  827. }
  828. if (si === 0 && preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
  829. preMeasureNumber = note?.sourceMeasure?.MeasureNumberXML
  830. allMeasures.push(note.sourceMeasure);
  831. }
  832. if (si === 0 && state.isSpecialBookCategory) {
  833. for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
  834. if (expression?.InstantaneousTempo?.beatUnit) {
  835. // 取最后一个有效的tempo
  836. beatUnit = expression.InstantaneousTempo.beatUnit;
  837. }
  838. }
  839. }
  840. // 判断是否是同一小节
  841. if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
  842. staveNoteIndex++
  843. } else {
  844. // staveIndex不同,重新赋值
  845. staveIndex = note.sourceMeasure?.MeasureNumberXML
  846. staveNoteIndex = 0
  847. }
  848. let measureSpeed = note.sourceMeasure.tempoInBPM;
  849. const { metronomeNoteIndex } = iterator.currentMeasure;
  850. if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
  851. measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
  852. }
  853. // 当前的分轨
  854. let activeVerticalMeasureList: any = [];
  855. /**
  856. * bug: #9959
  857. * 多分轨合并展示,第一分轨又可能获取不到对应的音符,需要在当前小节中音符最多的分轨中去查找音符
  858. */
  859. // if (state.isCombineRender) {
  860. // const allTrackList = note.sourceMeasure.verticalMeasureList;
  861. // let maxIdx = 0, maxNote = 0;
  862. // allTrackList.forEach((item: any, index: number) => {
  863. // if (item?.vfVoices['1']?.tickables?.length > maxNote) {
  864. // maxIdx = index
  865. // maxNote = item?.vfVoices['1']?.tickables?.length
  866. // }
  867. // })
  868. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[maxIdx]] || [];
  869. // } else {
  870. // activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
  871. // }
  872. activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
  873. const { realValue } = iterator.currentTimeStamp;
  874. const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(
  875. iterator.currentMeasure.activeTimeSignature,
  876. iterator.currentMeasure.duration
  877. );
  878. let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
  879. if (customNoteRealValue[i]) {
  880. // console.log(NoteRealValue, customNoteRealValue[i])
  881. NoteRealValue = customNoteRealValue[i];
  882. }
  883. if (isDouble && currentTime > 0) {
  884. if (currentTime != NoteRealValue) {
  885. // console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
  886. NoteRealValue = currentTime;
  887. }
  888. }
  889. // note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
  890. // 管乐迷,按自定义按读取到的音符时值
  891. if (customNoteCurrentTime) {
  892. if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
  893. // console.log(NoteRealValue, currentTimes[i + 1])
  894. NoteRealValue = currentTimes[i + 1];
  895. }
  896. }
  897. let relativeTime = usetime;
  898. let beatSpeed = 0;
  899. // 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度,否则mp3速度不对
  900. if (measureSpeed !== baseSpeed && !hasVaryingSpeed) {
  901. beatSpeed = baseSpeed || measureSpeed || 100
  902. } else {
  903. beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  904. }
  905. // let beatSpeed = measureSpeed || baseSpeed
  906. // 如果有节拍器,需要将节拍器的时间算出来
  907. if (i === 0) {
  908. fixtime += getFixTime(beatSpeed);
  909. state.fixtime = fixtime;
  910. // console.log("fixtime:", fixtime, '速度:', beatSpeed, "state.isSpecialBookCategory:", state.isSpecialBookCategory, 'state.isOpenMetronome:', state.isOpenMetronome);
  911. }
  912. // console.log(getTimeByBeatUnit(beatUnit, measureSpeed, iterator.currentMeasure.activeTimeSignature.Denominator))
  913. let gradualLength = 0;
  914. let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
  915. gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
  916. gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
  917. if (!gradualSpeed || gradualSpeed.length < 2) {
  918. gradualSpeed = createSpeedInfo(gradualChange, speed);
  919. }
  920. // console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
  921. const measureListIndex = iterator.currentMeasure.measureListIndex;
  922. // 计算相差时间按照比例分配到所有音符上
  923. if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
  924. const withInRangeNote = state.gradual.find((item, index) => {
  925. const nextItem: any = state.gradual[index + 1];
  926. return (
  927. item[0].measureIndex <= measureListIndex &&
  928. item[1]?.measureIndex! >= measureListIndex &&
  929. (!nextItem || nextItem?.[0].measureIndex !== measureListIndex)
  930. );
  931. });
  932. const [first, last] = withInRangeNote || [];
  933. if (first && last) {
  934. // 小节数量
  935. const continuous = last.measureIndex - first.measureIndex;
  936. // 开始小节内
  937. const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
  938. // 结束小节内
  939. const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
  940. // 范围内小节
  941. const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
  942. if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
  943. const startTime = state.gradualTimes[first.measureIndex];
  944. const endTime = state.gradualTimes[last.measureIndex];
  945. if (startTime && endTime) {
  946. const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
  947. const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
  948. gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
  949. }
  950. }
  951. }
  952. } else if (state.appName === "GYM" && gradualChange && gradualSpeed && (gradualChange.startXmlNoteIndex === si || gradualChangeIndex > 0)) {
  953. const startSpeed = gradualSpeed[0] - (gradualSpeed[1] - gradualSpeed[0]);
  954. const { resetXmlNoteIndex, endXmlNoteIndex } = gradualChange;
  955. const noteDiff = endXmlNoteIndex;
  956. let stepSpeed = (gradualSpeed[gradualSpeed.length - 1] - startSpeed) / noteDiff;
  957. stepSpeed = note.DotsXml ? stepSpeed / 1.5 : stepSpeed;
  958. if (gradualChangeIndex < noteDiff) {
  959. const tempSpeed = Math.ceil(speed + stepSpeed * gradualChangeIndex);
  960. let tmpSpeed = getTimeByBeatUnit(beatUnit, tempSpeed, iterator.currentMeasure.activeTimeSignature.Denominator);
  961. const maxLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
  962. // speed += stepSpeeds.reduce((a, b) => a + b, 0)
  963. speed += Math.ceil(stepSpeed * (gradualChangeIndex + 1));
  964. tmpSpeed = getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator);
  965. const minLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
  966. gradualLength = (maxLength + minLength) / 2;
  967. } else if (resetXmlNoteIndex > gradualChangeIndex) {
  968. speed = allNotes[i - 1]?.speed;
  969. }
  970. beatSpeed =
  971. (state.isSpecialBookCategory ? getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator) : baseSpeed) || 1;
  972. const isEnd = !(gradualChangeIndex < noteDiff) && !(resetXmlNoteIndex > gradualChangeIndex);
  973. gradualChangeIndex++;
  974. if (isEnd) {
  975. gradualChangeIndex = 0;
  976. gradualChange = undefined;
  977. gradualSpeed = undefined;
  978. stepSpeeds = [];
  979. }
  980. }
  981. const _noteLength = NoteRealValue;
  982. // 当前音符的持续时长,当前音符的RealValue值*拍数*(60/后台设置的基准速度)
  983. let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  984. // 小节时长
  985. const measureLength = vRealValue * vDenominator * (60 / beatSpeed);
  986. // console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
  987. // console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
  988. usetime += noteLength;
  989. relaMeasureLength += noteLength;
  990. let relaEndtime = noteLength + relativeTime;
  991. // console.log('relaEndtime',noteLength, relativeTime)
  992. const fixedKey = note.fixedKey || 0;
  993. // const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
  994. const svgElement = activeVerticalMeasureList[0]?.vfVoices['1']?.tickables[staveNoteIndex];
  995. // console.log('si',si,i)
  996. // console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
  997. if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
  998. continue;
  999. }
  1000. // console.log(iterator.currentMeasure)
  1001. // 如果是弱起就补齐缺省的时长,midi音频不需要考虑弱起
  1002. if (i === 0 && !state.isAppPlay) {
  1003. let _firstMeasureRealValue = 0;
  1004. const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
  1005. //计算第一个小节里面的音符时值是否等于整个小节的时值
  1006. staffEntries.forEach((_a: any) => {
  1007. if (_a?.sourceStaffEntry?.voiceEntries?.[0]?.notes?.[0]?.length?.realValue) {
  1008. _firstMeasureRealValue += _a.sourceStaffEntry.voiceEntries[0].notes[0].length.realValue;
  1009. }
  1010. });
  1011. if (_firstMeasureRealValue < vRealValue) {
  1012. // console.log(_firstMeasureRealValue, vRealValue)
  1013. // 如果是弱起,将整个小节的时值减去该小节所有音符相加的时值,就是缺省的时值
  1014. difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1015. }
  1016. /**
  1017. * 管乐迷,部分弱起的曲目,mp3制作不标准,没有按照补齐弱起后的时间进行制作,需要单独处理
  1018. * 2670
  1019. */
  1020. if (["2670"].includes(state.cbsExamSongId)) {
  1021. // fixtime -= _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1022. } else {
  1023. if (difftime > 0) {
  1024. fixtime += difftime;
  1025. state.fixtime = fixtime;
  1026. }
  1027. }
  1028. // 管乐迷 diff获取不准确时, 弱起补齐
  1029. if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
  1030. // difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
  1031. // fixtime += difftime;
  1032. }
  1033. // 如果是evxml,fixtime取读取xml的值
  1034. if (state.isEvxml) {
  1035. fixtime = state.evXmlBeginTime ? state.evXmlBeginTime : fixtime
  1036. state.fixtime = fixtime
  1037. }
  1038. console.log('节拍器时间',fixtime,state.evXmlBeginTime)
  1039. }
  1040. let stave = activeVerticalMeasureList[0]?.stave;
  1041. if (note.sourceMeasure.multipleRestMeasures) {
  1042. totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures;
  1043. multipleRestMeasures = 0;
  1044. }
  1045. if (multipleRestMeasures < totalMultipleRestMeasures) {
  1046. multipleRestMeasures++;
  1047. } else {
  1048. multipleRestMeasures = 0;
  1049. totalMultipleRestMeasures = 0;
  1050. }
  1051. // console.log(note.tie)
  1052. // console.log('👀看看endtime', duration, relaEndtime, fixtime, i)
  1053. // console.log('频率',note?.pitch?.frequency,i)
  1054. /**
  1055. * evxml的曲子,如果曲谱xml中带有times信息,则音符时值优先取times中的值
  1056. */
  1057. let evNoteStartTime = 0, evNoteEndTime = 0;
  1058. if (state.isEvxml && note?.noteTimeInfo?.length) {
  1059. const idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0
  1060. evNoteStartTime = note?.noteTimeInfo[idx]?.begin
  1061. evNoteEndTime = note?.noteTimeInfo[idx]?.end
  1062. relativeTime = evNoteStartTime - fixtime
  1063. // usetime = evNoteStartTime - fixtime
  1064. }
  1065. svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
  1066. const nodeDetail = {
  1067. isStaccato: note.voiceEntry.isStaccato(),
  1068. isRestFlag: note.isRestFlag,
  1069. noteId: note.NoteToGraphicalNoteObjectId,
  1070. measureListIndex: note.sourceMeasure.measureListIndex,
  1071. MeasureNumberXML: note.sourceMeasure.MeasureNumberXML, // 当前的小节数,(从1开始)
  1072. _noteLength: _noteLength,
  1073. svgElement: svgElement,
  1074. frequency: note?.pitch?.frequency || -1,
  1075. nextFrequency: note?.pitch?.nextFrequency || -1,
  1076. prevFrequency: note?.pitch?.prevFrequency || -1,
  1077. difftime,
  1078. octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
  1079. speed,
  1080. beatSpeed,
  1081. i,
  1082. si,
  1083. stepSpeeds,
  1084. measureOpenIndex: allMeasures.length - 1,
  1085. measures,
  1086. tempoInBPM: note.sourceMeasure.tempoInBPM,
  1087. measureLength,
  1088. relaMeasureLength,
  1089. id: svgElement?.attrs.id,
  1090. note: note.halfTone + 12, // see issue #224
  1091. fixtime, // 弱起补充的时间
  1092. relativeTime: retain(relativeTime),
  1093. time: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + fixtime), // 开始播放的时间
  1094. endtime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + fixtime), // 播放完成的时间
  1095. relaEndtime: retain(relaEndtime),
  1096. realValue,
  1097. halfTone: note.halfTone,
  1098. noteElement: note,
  1099. fixedKey,
  1100. realKey: 0,
  1101. duration: 0,
  1102. formatLyricsEntries: formatLyricsEntries(note),
  1103. stave,
  1104. firstVerticalMeasure: activeVerticalMeasureList[0],
  1105. noteLength: 1,
  1106. osdmContext: osmd,
  1107. speedbeatUnit: beatUnit,
  1108. multipleRestMeasures: multipleRestMeasures, // 当前合并小节的索引,从1开始到当前的totalMultipleRestMeasures结束,
  1109. totalMultipleRestMeasures, // 当前小节总的合并小节数
  1110. measureSpeed, // 小节速度
  1111. maxNoteNum: note.maxNoteNum, // 当前小节音符最多的分轨的音符数量
  1112. };
  1113. // 如果是妙极客的曲子,并且第二遍循环播放需要等待时间,并且是第二遍循环的第一个小节的第一个音符
  1114. if (state.isEvxml && state.secondEvXmlBeginTime && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
  1115. nodeDetail.time = nodeDetail.time + state.secondEvXmlBeginTime;
  1116. nodeDetail.endtime = nodeDetail.endtime + state.secondEvXmlBeginTime;
  1117. usetime = usetime + state.secondEvXmlBeginTime;
  1118. relativeTime = relativeTime + state.secondEvXmlBeginTime;
  1119. }
  1120. nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
  1121. nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
  1122. let tickables = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables || [];
  1123. if ([121].includes(state.subjectId)) {
  1124. tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
  1125. }
  1126. // console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
  1127. // console.log('👀看看endtime', nodeDetail.duration, relaEndtime, fixtime, i)
  1128. // console.log('音符时间',nodeDetail.i,nodeDetail.time,nodeDetail.endtime)
  1129. tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
  1130. const maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
  1131. nodeDetail.noteLength = maxNum || 1;
  1132. allNotes.push(nodeDetail);
  1133. allNoteId.push(nodeDetail.id);
  1134. measures.push(nodeDetail);
  1135. /**
  1136. * bug: #9877
  1137. * 多分轨合并展示的曲子,不同分轨,同一小节音符的数量可能不能,不能只通过tickables的长度判断该小节的音符数量
  1138. */
  1139. if (si < maxNum - 1) {
  1140. si++;
  1141. } else {
  1142. si = 0;
  1143. relaMeasureLength = 0;
  1144. measures = [];
  1145. }
  1146. }
  1147. i++;
  1148. }
  1149. // 按照时间轴排序
  1150. const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => ({ ...item, i: index }));
  1151. // const sortArray = allNotes.sort((a, b) => a.time - b.time).map((item, index) => ({ ...item, i: index }));
  1152. console.timeEnd("音符跑完时间");
  1153. try {
  1154. osmd.cursor.reset();
  1155. } catch (error) {}
  1156. state.activeMeasureIndex = sortArray[0].MeasureNumberXML;
  1157. return sortArray;
  1158. };
  1159. /** 获取小节之间的连音线,仅同音高*/
  1160. export const getNoteByMeasuresSlursStart = (note: any) => {
  1161. let activeNote = note;
  1162. let tieNote;
  1163. if (note.noteElement.tie && note.noteElement.tie.StartNote) {
  1164. tieNote = note.noteElement.tie.StartNote;
  1165. }
  1166. if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
  1167. const arr: any = []
  1168. for (const note of state.times) {
  1169. if (tieNote === note.noteElement) {
  1170. arr.push(note)
  1171. }
  1172. }
  1173. if (arr.length) {
  1174. return arr.find((n: any) => n.i === (note.i - 1)) || arr[0]
  1175. }
  1176. }
  1177. return activeNote;
  1178. };
  1179. // 通过xml信息获取重播的小节信息
  1180. const parseXmlToRepeat = (repeats: any) => {
  1181. if (!repeats.length) return
  1182. let repeatInfo: any = []
  1183. // 重复开始小节,结束小节
  1184. let start = 0, end = 0
  1185. for (let i = 0; i < repeats.length; i++) {
  1186. const element = repeats[i];
  1187. const direction = element.getAttribute('direction')
  1188. let parentElement = element.parentNode
  1189. while (parentElement && parentElement.tagName !== 'measure') {
  1190. parentElement = parentElement.parentNode
  1191. }
  1192. let notesNumber = parentElement.getAttribute('number') // 第多少小节,从1开始
  1193. notesNumber = notesNumber ? Number(notesNumber) : 0
  1194. if (direction === 'forward') {
  1195. start = notesNumber
  1196. } else if (direction === 'backward') {
  1197. end = notesNumber
  1198. repeatInfo.push({
  1199. start,
  1200. end
  1201. })
  1202. }
  1203. }
  1204. state.repeatInfo = repeatInfo
  1205. // console.log('重播',repeatInfo)
  1206. }
  1207. // 校验当前选段是否满足重播条件
  1208. export const verifyCanRepeat = (startNum: number, endNum: number) => {
  1209. let repeatIdx = -1
  1210. if (state.repeatInfo.length) {
  1211. for (let i = state.repeatInfo.length - 1; i >= 0; i--) {
  1212. const { start, end } = state.repeatInfo[i];
  1213. if (startNum <= start && endNum >= end) {
  1214. repeatIdx = i
  1215. return {
  1216. repeatIdx,
  1217. canRepeat: true
  1218. }
  1219. break;
  1220. }
  1221. }
  1222. return {
  1223. repeatIdx,
  1224. canRepeat: false
  1225. }
  1226. } else {
  1227. return {
  1228. repeatIdx,
  1229. canRepeat: false
  1230. }
  1231. }
  1232. }
  1233. // 处理妙极客xml谱面
  1234. const customizationXml = (xmlParse: any) => {
  1235. const credits: any = Array.from(xmlParse.querySelectorAll('credit'));
  1236. const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
  1237. const graces: any = Array.from(xmlParse.querySelectorAll('grace'));
  1238. const measures: any[] = Array.from(xmlParse.getElementsByTagName("measure"));
  1239. if (credits && credits.length) {
  1240. for (const credit of credits) {
  1241. if (credit.getElementsByTagName("credit-type")?.[0]?.textContent === 'lyricist') {
  1242. const creditWord = credit.getElementsByTagName("credit-words")
  1243. creditWord?.[0].setAttribute('justify', 'right')
  1244. }
  1245. }
  1246. }
  1247. if (creators && creators.length) {
  1248. for (const creator of creators) {
  1249. if (creator.getAttribute('type') === 'lyricist') {
  1250. // creator.textContent = '测试一下1';
  1251. }
  1252. }
  1253. }
  1254. // 妙极客xml的倚音(grace)标签需要加上slash=yes属性
  1255. if (graces && graces.length) {
  1256. for (const grace of graces) {
  1257. grace?.setAttribute('slash','yes');
  1258. // console.log(grace,'倚音')
  1259. }
  1260. }
  1261. // 妙极客xml部分小节没有音符,只有Segno,该小节不需要渲染,表示的是反复标记
  1262. for (const measure of measures) {
  1263. const hasNote = measure.getElementsByTagName("note").length;
  1264. const hasSegno = measure.getElementsByTagName("segno").length;
  1265. const sounds = Array.from(measure.getElementsByTagName("sound"));
  1266. const hasSoundSegno = sounds.some((item: any) => item.getAttribute('segno') === 'segno' );
  1267. if (!hasNote && hasSegno && hasSoundSegno) {
  1268. const parent = measure.parentNode;
  1269. parent.removeChild(measure);
  1270. }
  1271. }
  1272. }
  1273. // 计算evxml的起始播放时间
  1274. const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
  1275. // xml拍号数
  1276. const xmlNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('num');
  1277. const denNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('den');
  1278. const xmlNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('num');
  1279. const denNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('den');
  1280. // 第一个音符的起始时间
  1281. const firstMeasure = xmlParse.getElementsByTagName("measure")[0];
  1282. if (firstMeasure) {
  1283. const firstNoteBeginTime = firstMeasure.getElementsByTagName("times")[0]?.getElementsByTagName("time")[0]?.getAttribute('begin');
  1284. state.evXmlBeginTime = firstNoteBeginTime ? firstNoteBeginTime / 1000 : xmlNum ? 60 / state.originSpeed * xmlNum * 4/denNum : 0;
  1285. state.secondEvXmlBeginTime = firstNoteBeginTime ? 0 : xmlNum2 ? 60 / state.originSpeed * xmlNum2 * 4/denNum2 : 0;
  1286. const hasTimeGap = xmlParse.getElementsByTagName("timegap").length > 0;
  1287. const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
  1288. console.log('🚀 ~ evxml解析','有timegap:',hasTimeGap,'有times:',hasTimes)
  1289. }
  1290. // if (!hasTimeGap && !hasTimes) {
  1291. // state.noTimes.push(xmlUrl)
  1292. // }
  1293. }
  1294. /**
  1295. * 兼容处理xml声部移调
  1296. * 打谱软件可能会自动处理移调,这类型的xml就不用通过程序移调了
  1297. * 没有通过软件处理的移调xml,才需要通过程序处理
  1298. * 判读规则:只处理独奏的,不处理合奏的,
  1299. * <instrument-name></instrument-name>标签的值为:Tenor Recorder(竖笛)、Panpipes(排箫)、Ocarina(陶笛)、Woodwind(葫芦丝)、空的和solo,需要程序处理移调
  1300. */
  1301. export const compatibleXmlPitchVoice = (xmlParse: any) => {
  1302. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1303. const partListNames = partNames.map((item: any) => item[0]?.textContent?.trim().toLocaleUpperCase !== "COMMON");
  1304. if (partListNames.length == 1) {
  1305. const instrumentNames = Array.from(xmlParse.getElementsByTagName('instrument-name')) || [];
  1306. // @ts-ignore
  1307. const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
  1308. // console.log('instrument名称',instrumentName)
  1309. // 是否需要程序处理移调
  1310. let xmlNeedAdjustVoice = false;
  1311. switch (state.musicalCodeId) {
  1312. case 37:
  1313. case 38:
  1314. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('tenor recorder') ? true : false
  1315. break;
  1316. case 33:
  1317. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('panpipes') ? true : false
  1318. break;
  1319. case 34:
  1320. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('ocarina') ? true : false
  1321. break;
  1322. case 35:
  1323. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('woodwind') ? true : false
  1324. break;
  1325. case 39:
  1326. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('whistling') ? true : false
  1327. break;
  1328. default:
  1329. xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') ? true : false
  1330. break;
  1331. }
  1332. (window as any).xmlNeedAdjustVoice = xmlNeedAdjustVoice
  1333. }
  1334. }