formateMusic.ts 76 KB

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