formateMusic.ts 75 KB

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