formateMusic.ts 60 KB

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