formateMusic.ts 76 KB

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