formateMusic.ts 71 KB

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