metronome.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /**
  2. * 曲谱节拍器
  3. * auth: lsq
  4. * time: 2022.11.14
  5. */
  6. import { reactive, watch } from "vue";
  7. import { tickUrl as tick, tockUrl as tock } from "/src/constant/audios";
  8. import { browser } from "/src/utils/index";
  9. import state from "/src/state";
  10. import { Howl } from "howler";
  11. import tockAndTick from "/src/constant/tockAndTick.json";
  12. import tickWav from "/src/assets/tick.mp3";
  13. import tockWav from "/src/assets/tock.mp3";
  14. import { audioData as audioDataState } from "../view/audio-list"
  15. type IOptions = {
  16. speed: number;
  17. };
  18. const browserInfo = browser();
  19. let tipsTimer: any = null; // 光标提示定时器
  20. // HTMLAudioElement 音频
  21. const audioData = reactive({
  22. tick: null as unknown as HTMLAudioElement,
  23. tock: null as unknown as HTMLAudioElement,
  24. });
  25. let tickTockPlayTime = 0;
  26. export const metronomeData = reactive({
  27. disable: true,
  28. initPlayerState: false,
  29. lineShow: false,
  30. isClick: false,
  31. metro: null as unknown as Metronome,
  32. metroList: [] as number[],
  33. activeList: [] as number[],
  34. metroMeasure: [] as any[],
  35. activeIndex: null as any,
  36. activeMetro: {} as any,
  37. cursorMode: 2 as number, // 光标模式:1:音符指针;2:节拍指针;3:关闭指针
  38. cursorTips: '' as string, // 光标模式提示文字
  39. followAudioIndex: 1, // 当前的拍数
  40. totalNumerator: 2, // 总拍数
  41. firstBeatTypeArr:[] as number[] // 第一小节的节拍
  42. });
  43. watch(
  44. () => metronomeData.cursorMode,
  45. () => {
  46. const img: HTMLElement = document.querySelector("#cursorImg-0")!;
  47. if (img) {
  48. switch (metronomeData.cursorMode) {
  49. case 1:
  50. img.classList.remove("lineHide");
  51. img.style.opacity = 'inherit'
  52. metronomeData.cursorTips = '您已切换到指针跟随音符播放';
  53. img.style.opacity = 'inherit'
  54. break;
  55. case 2:
  56. img.classList.add("lineHide");
  57. img.style.opacity = 'inherit'
  58. metronomeData.cursorTips = '您已切换到指针跟随节拍播放';
  59. // console.log('光标',img)
  60. break;
  61. case 3:
  62. img.style.opacity = '0'
  63. metronomeData.cursorTips = '您已关闭指针显示';
  64. // console.log('隐藏光标')
  65. break;
  66. default:
  67. break;
  68. }
  69. hideCursorTip()
  70. }
  71. }
  72. );
  73. // 切换隐藏光标
  74. const toggleLine = () => {
  75. if (!metronomeData.lineShow) return;
  76. const img: HTMLElement = document.querySelector("#cursorImg-0")!;
  77. if (img) {
  78. if (state.times[state.activeNoteIndex].multipleRestMeasures) {
  79. img.classList.remove("lineHide");
  80. } else {
  81. img.classList.add("lineHide");
  82. }
  83. }
  84. };
  85. watch(
  86. () => metronomeData.lineShow,
  87. () => {
  88. const img: HTMLElement = document.querySelector("#cursorImg-0")!;
  89. if (img) {
  90. if (metronomeData.lineShow) {
  91. img.classList.add("lineHide");
  92. } else {
  93. img.classList.remove("lineHide");
  94. }
  95. }
  96. }
  97. );
  98. class Metronome {
  99. playType = "tick";
  100. source = null as any; // 创建音频源头
  101. source1 = null as any;
  102. source2 = null as any;
  103. constructor(option?: IOptions) {}
  104. init(times: any[]) {
  105. this.calculation(times);
  106. metronomeData.activeList = [];
  107. this.initPlayer()
  108. }
  109. initPlayer() {
  110. // if (!this.source1) {
  111. // this.source1 = this.loadAudio1();
  112. // }
  113. // if (!this.source2) {
  114. // this.source2 = this.loadAudio2();
  115. // }
  116. // metronomeData.initPlayerState = true;
  117. if(metronomeData.initPlayerState) return
  118. Promise.all([this.createAudio(tickWav), this.createAudio(tockWav)]).then(
  119. ([tick, tock]) => {
  120. if (tick) {
  121. audioData.tick = tick;
  122. }
  123. if (tock) {
  124. audioData.tock = tock;
  125. }
  126. metronomeData.initPlayerState = true;
  127. }
  128. );
  129. }
  130. createAudio = (src: string): Promise<HTMLAudioElement | null> => {
  131. return new Promise((resolve) => {
  132. // const a = new Audio(src + '?v=' + Date.now());
  133. const a = new Audio(src);
  134. a.load();
  135. a.onloadedmetadata = () => {
  136. resolve(a);
  137. };
  138. a.onerror = () => {
  139. resolve(null);
  140. };
  141. });
  142. };
  143. // 播放
  144. sound = (currentTime: number) => {
  145. let index = -1;
  146. let activeMetro = -1;
  147. for (let i = 0; i < metronomeData.metroList.length; i++) {
  148. const item = metronomeData.metroList[i];
  149. if (currentTime >= item) {
  150. // console.log(currentTime , item)
  151. index = i;
  152. activeMetro = item;
  153. } else {
  154. break;
  155. }
  156. }
  157. if (index > -1 && metronomeData.activeIndex !== index) {
  158. metronomeData.activeIndex = index;
  159. // console.log("播放", metronomeData.activeIndex);
  160. metronomeData.activeMetro = this.getStep(activeMetro);
  161. // console.log("🚀 ~ metronomeData.activeMetro",metronomeData.activeMetro.measureNumberIndex, metronomeData.activeMetro.index)
  162. tickTockPlayTime = currentTime
  163. this.playAudio();
  164. metronomeData.isClick = false;
  165. return;
  166. }
  167. // toggleLine()
  168. metronomeData.isClick = false;
  169. };
  170. // 暂停的时候,点击音符,需要找到对应的节拍器的位置
  171. findMetronomePosition = (currentTime: number) => {
  172. console.log('取消选段1111',currentTime)
  173. const originTime = currentTime;
  174. // if (!state.sectionStatus){
  175. // currentTime = setCurrentTime(currentTime);
  176. // }
  177. let index = -1;
  178. let activeMetro = -1;
  179. for (let i = 0; i < metronomeData.metroList.length; i++) {
  180. const item = metronomeData.metroList[i];
  181. if (currentTime >= item) {
  182. // console.log(currentTime , item)
  183. index = i;
  184. activeMetro = item;
  185. } else {
  186. break;
  187. }
  188. }
  189. if (index > -1 && metronomeData.activeIndex !== index) {
  190. metronomeData.activeIndex = index;
  191. // console.log("节拍器播放", '节拍器索引:',metronomeData.activeIndex, '节拍器时间:',currentTime, '实际时间:',originTime,'xml计算的时间:',metronomeData.metroList[metronomeData.activeIndex]);
  192. metronomeData.activeMetro = this.getStep(activeMetro);
  193. console.log("🚀 ~ metronomeData.activeMetro",metronomeData.activeMetro.measureNumberIndex, metronomeData.activeMetro.index)
  194. tickTockPlayTime = currentTime
  195. // this.playAudio();
  196. metronomeData.isClick = false;
  197. return;
  198. }
  199. metronomeData.isClick = false;
  200. if (currentTime === 0) {
  201. metronomeData.activeMetro = {}
  202. }
  203. };
  204. // 播放
  205. playAudio = () => {
  206. // 关闭定时器节拍器
  207. return
  208. /* 如果是 评测模式且不为MIDI并且节拍器资源加载成功的时候 不运行节拍器播放*/
  209. if (state.modeType === "practise" && state.playMode !== "MIDI") {
  210. if(state.playType === "play" && state.playSource === "music" && audioDataState.songCollection.beatSongEle){
  211. return
  212. }
  213. if(state.playType === "play" && state.playSource === "background" && audioDataState.songCollection.beatBackgroundEle){
  214. return
  215. }
  216. if(state.playType === "sing" && state.playSource === "music" && audioDataState.songCollection.beatFanSongEle){
  217. return
  218. }
  219. if(state.playType === "sing" && state.playSource === "background" && audioDataState.songCollection.beatBanSongEle){
  220. return
  221. }
  222. if(state.playType === "sing" && state.playSource === "mingSong" && audioDataState.songCollection.beatMingSongEle){
  223. return
  224. }
  225. }
  226. // console.log("播放自带的节拍器 233333")
  227. if (!metronomeData.initPlayerState || state.playState === 'paused') return;
  228. const beatVolume = state.setting.beatVolume / 100
  229. // this.source = metronomeData.activeMetro?.index === 0 ? this.source1 : this.source2;
  230. // this.source.volume(metronomeData.disable || state.playState === 'paused' ? 0 : beatVolume);
  231. // Audio 播放音频
  232. this.source = metronomeData.activeMetro?.index === 0 ? audioData.tick : audioData.tock;
  233. this.source.volume = metronomeData.disable ? 0 : beatVolume;
  234. if (this.source.volume <= 0) {
  235. this.source.muted = true
  236. } else {
  237. this.source.muted = false
  238. }
  239. // console.log('节拍器播放的时间',tickTockPlayTime)
  240. this.source.play();
  241. };
  242. /**
  243. * 跟练模式播放,跟练模式没有曲子音频播放器
  244. */
  245. simulatePlayAudio = () => {
  246. // console.log(333, metronomeData.followAudioIndex)
  247. if (!metronomeData.initPlayerState) return;
  248. const beatVolume = state.setting.beatVolume / 100
  249. // this.source = metronomeData.followAudioIndex === 1 ? this.source1 : this.source2;
  250. // Audio 播放音频
  251. this.source = metronomeData.followAudioIndex === 1 ? audioData.tick : audioData.tock;
  252. // this.source.volume(metronomeData.disable ? 0 : beatVolume);
  253. this.source.volume = metronomeData.disable ? 0 : beatVolume
  254. /**
  255. * https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLMediaElement/volume
  256. * volume属性在部分ios手机的Safari浏览器不被支持
  257. */
  258. if (this.source.volume <= 0) {
  259. this.source.muted = true
  260. } else {
  261. this.source.muted = false
  262. }
  263. // console.log('音量',this.source,this.source.volume)
  264. this.source.play();
  265. metronomeData.followAudioIndex += 1;
  266. metronomeData.followAudioIndex = metronomeData.followAudioIndex > metronomeData.totalNumerator ? 1 : metronomeData.followAudioIndex;
  267. };
  268. // 切换
  269. selectPlay() {}
  270. loadAudio1 = () => {
  271. return new Howl({
  272. src: tockAndTick.tick,
  273. // 如果是ios手机,需要强制使用audio,不然部分系统版本第一次播放没有声音
  274. // html5: browserInfo.ios,
  275. });
  276. };
  277. loadAudio2 = () => {
  278. return new Howl({
  279. src: tockAndTick.tock,
  280. // html5: browserInfo.ios,
  281. });
  282. };
  283. getStep(time: number) {
  284. for (let i = 0; i < metronomeData.metroMeasure.length; i++) {
  285. const list = metronomeData.metroMeasure[i];
  286. const item = list.find((n: any) => n.time === time);
  287. if (item) {
  288. // console.log('index',item)
  289. return item;
  290. }
  291. }
  292. return {};
  293. }
  294. // 计算 所有的拍子的时间
  295. calculation(times: any[]) {
  296. // console.log("🚀 ~ times", times);
  297. // 1.统计有多少小节
  298. const measures: any[] = [];
  299. let xmlNumber = -1;
  300. let isDiff = false //弱起时间不够补的时候
  301. for (let i = 0; i < times.length; i++) {
  302. const note = times[i];
  303. const measureNumberXML = note.MeasureNumberXML;
  304. // console.log("🚀 ~ note?.noteElement?.sourceMeasure", note?.noteElement?.sourceMeasure)
  305. // console.log("🚀 ~ measureNumberXML", measureNumberXML, note)
  306. // console.log("🚀 ~ measureNumberXML", note)
  307. const measureListIndex = measureNumberXML - 1;
  308. // 当渐快渐慢的时候 不播节拍器
  309. if(isWithinRange(state.gradual, measureListIndex)){
  310. xmlNumber = measureNumberXML;
  311. continue
  312. }
  313. if (measureNumberXML > -1) {
  314. if (measureNumberXML != xmlNumber) {
  315. // 弱起的时候 根据音符结尾时间减去音符开头时间,得到的不是正常小节的时间,然后平均分配节拍之后,当前节拍间隔会非常短 这里弱起取整个小节的时间
  316. // 当小节时间 减去音符时间,前奏没有预留时间时候,从歌词开始唱的那里开始响节拍器
  317. let startTime = note.measures[0].time
  318. if(i === 0 && note.measures[0].difftime>0){
  319. startTime = note.measures[note.measures.length - 1].endtime - note.measures[0].measureLength
  320. if(startTime < 0){
  321. isDiff = true
  322. }
  323. }
  324. if(isDiff) {
  325. // 当前小节有歌词,开放弱起节拍器
  326. let isLyric = false
  327. let noteIndex = 0
  328. while(!isLyric && noteIndex<note.measures.length){
  329. isLyric = !!note.measures[noteIndex]?.formatLyricsEntries?.length
  330. noteIndex ++
  331. }
  332. isDiff = !isLyric
  333. }
  334. if(isDiff){
  335. xmlNumber = measureNumberXML;
  336. continue
  337. }
  338. // 最后一小节的时间 有可能和下一小节开始时间接不上
  339. const { time, endtime, noteLengthTime } = note.measures[note.measures.length - 1]
  340. let nextNoteStartTime = times[note.measures[note.measures.length - 1].i + 1]?.time
  341. let noteEndTime = 0
  342. if(!nextNoteStartTime){
  343. // 当不够的时候补上时值
  344. noteEndTime = time + noteLengthTime > endtime ? time + noteLengthTime : endtime
  345. }else{
  346. if(Math.abs(nextNoteStartTime - endtime)*1000< 10){
  347. // 当首位本来就是相连的
  348. noteEndTime = endtime
  349. }else{
  350. // 当首位不相连,差值大于这个音符的持续时间的时候取这个音符的时间(防止有间奏的连起来时间太长),否则直接取后一个音符的开始时间
  351. noteEndTime = nextNoteStartTime - time > noteLengthTime ? time + noteLengthTime : nextNoteStartTime
  352. }
  353. }
  354. const m = {
  355. measureNumberXML: measureNumberXML,
  356. measureNumberIndex: measureListIndex,
  357. CompoundTempo: note?.noteElement?.sourceMeasure?.CompoundTempo || "",
  358. numerator: note?.noteElement?.sourceMeasure?.ActiveTimeSignature?.numerator || 0,
  359. denominator: note?.noteElement?.sourceMeasure?.ActiveTimeSignature?.denominator || 0,
  360. start: startTime,
  361. end: noteEndTime,
  362. time: noteEndTime - startTime,
  363. stave_x: note?.noteElement?.sourceMeasure?.verticalMeasureList?.[0]?.stave?.x || 0,
  364. end_x: note?.stave?.end_x || 0 || 0,
  365. stepList: [] as number[],
  366. svgs: [] as any[],
  367. isRestFlag: note.isRestFlag,
  368. };
  369. /**
  370. * bug:#9877
  371. * 多分轨合并显示,不同分轨的音符数量可能不同
  372. */
  373. let measureArr = note.measures;
  374. if (state.isCombineRender) {
  375. measureArr = measureArr.filter((item: any) => item.MeasureNumberXML === m.measureNumberXML)
  376. }
  377. m.stepList = calculateMetroStep(measureArr, m);
  378. measures.push(m);
  379. xmlNumber = measureNumberXML;
  380. }
  381. }
  382. }
  383. //console.log(measures, measures.length,'小节汇总');
  384. let metroList: number[] = [];
  385. const metroMeasure: any[] = [];
  386. console.log("节拍器 每一小节时间:", measures)
  387. console.log("节拍器 间隔:", measures.map(item => {
  388. return {
  389. time: item.time,
  390. measureNumberXML: item.measureNumberXML
  391. }
  392. }))
  393. try {
  394. for (let i = 0; i < measures.length; i++) {
  395. const measure = measures[i];
  396. // 87拍和45拍要根据小节返回的CompoundTempo特殊处理
  397. const beatTypeArr = getBeatTypeArr(measure.numerator, measure.denominator, measure.CompoundTempo)
  398. const CompoundTempoArr = beatTypeArr.map((beatType:number) => {
  399. return Math.abs(beatType*measure.numerator)
  400. })
  401. if(i===0){
  402. metronomeData.firstBeatTypeArr = beatTypeArr
  403. }
  404. metroMeasure[i] = [] as number[];
  405. // 根据有几个拍子,划分成几份
  406. const widthStep = 100 / (beatTypeArr.length+1);
  407. // 当前拍子的组合数(2+3+2,3+2)中的数字
  408. let beatNum = 0;
  409. // if (measure.measureNumberXML == 98) {
  410. // debugger
  411. // }
  412. for (let j = 0; j < beatTypeArr.length; j++) {
  413. // 累加
  414. const beatMuit = Array(j).fill("").reduce((num:number,v:any,i:number) => {
  415. return num += Math.abs(beatTypeArr[i])
  416. }, 0) || 0
  417. const time = measure.time * beatMuit + measure.start;
  418. metroList.push(time);
  419. let left = "";
  420. // 当前拍子数对应的节拍位置索引
  421. let currentIdx = 0;
  422. if (j == 0) {
  423. currentIdx = 0
  424. } else {
  425. beatNum += CompoundTempoArr[j-1];
  426. currentIdx = beatNum
  427. }
  428. // 如果是87拍,并且是3+2+2的组合,第二拍的节拍指针需要定位到第四个音符的位置
  429. // if (measure.numerator === 7 && measure.denominator === 8 && measure.CompoundTempo === '3+2+2' && j === 1) {
  430. // currentIdx += 1;
  431. // }
  432. if (measure.stepList[currentIdx]) {
  433. left = measure.stepList[currentIdx] + "px";
  434. } else {
  435. const preLeft = measure.stepList[j - 1];
  436. left = !preLeft || preLeft.toString().indexOf("%") > -1 ? `${widthStep*(j+1)}%` : `${preLeft}px + ${widthStep}%`;
  437. measure.stepList[j] = left;
  438. }
  439. metroMeasure[i].push({
  440. isTick: beatTypeArr[j] < 0,
  441. index: j,
  442. time,
  443. left: left?.indexOf("%") > -1 ? `calc(${left})` : left,
  444. measureNumberXML: measure.measureNumberXML,
  445. isRestFlag: measure.isRestFlag,
  446. stepList: measure.stepList
  447. });
  448. }
  449. }
  450. } catch (error) {
  451. console.log(error);
  452. }
  453. console.log('节拍器',metroList, metroMeasure);
  454. // 5.得到所有的节拍时间
  455. metronomeData.metroList = metroList;
  456. metronomeData.metroMeasure = metroMeasure;
  457. // console.log(9999,metroList,7777,metroMeasure)
  458. metronomeData.activeMetro = metroMeasure[0]?.[0] || {};
  459. }
  460. }
  461. /** 获取节拍类型数组 */
  462. export function getBeatTypeArr(numerator?:number, denominator?:number, CompoundTempo?:string){
  463. const speedBeatUnit = state.speedBeatUnit
  464. const Numerator = numerator || state.osmd?.Sheet?.SheetPlaybackSetting?.Rhythm?.Numerator || 4
  465. const Denominator = denominator || state.osmd?.Sheet?.SheetPlaybackSetting?.Rhythm?.Denominator || 4
  466. let loopArr = []
  467. // 规则 负数代表重声,正数代表轻声
  468. switch (`${Numerator}/${Denominator}`) {
  469. case "2/2":
  470. loopArr = [-1/2, 1/2]
  471. break;
  472. case "3/2":
  473. loopArr = [-1/3, 1/3, 1/3]
  474. break;
  475. case "5/4":
  476. //5/4拍根据谱面的CompoundTempo来特殊处理
  477. if(CompoundTempo==="2+3"){
  478. loopArr = [-1/5, 1/5, -1/5, 1/5, 1/5]
  479. }else{
  480. loopArr = [-1/5, 1/5, 1/5, -1/5, 1/5]
  481. }
  482. break;
  483. case "3/8":
  484. // 3/8拍 速度为浮点4分音符时候特殊处理
  485. if(speedBeatUnit==="1/4."){
  486. loopArr = [-1/1]
  487. }else{
  488. loopArr = [-1/3, 1/3, 1/3]
  489. }
  490. break;
  491. case "6/8":
  492. loopArr = [-1/2, 1/2]
  493. break;
  494. case "7/8":
  495. //7/8拍根据谱面的CompoundTempo来特殊处理
  496. if(CompoundTempo==="2+2+3"){
  497. loopArr = [-2/7, 2/7, 3/7]
  498. }else if(CompoundTempo==="2+3+2"){
  499. loopArr = [-2/7, 3/7, 2/7]
  500. }else{
  501. loopArr = [-3/7, 2/7, 2/7]
  502. }
  503. break;
  504. case "9/8":
  505. loopArr = [-3/9, 3/9, 3/9]
  506. break;
  507. default:
  508. loopArr.push(-1/Numerator);
  509. for (let i = 1; i < Numerator; i++) {
  510. loopArr.push(1/Numerator);
  511. }
  512. break;
  513. }
  514. // console.log(loopArr, "loopArr")
  515. return loopArr
  516. }
  517. // 计算拍子的时值
  518. function calculateMetroStep(arr: any[], m: any): number[] {
  519. const measureLength = arr.reduce((total: number, item: any) => {
  520. total += item._noteLength;
  521. return total;
  522. }, 0);
  523. const clap = measureLength / m.numerator;
  524. if (arr.length === 1) {
  525. const wholeNote = arr[0].svgElement;
  526. if (wholeNote && !wholeNote.isRest()) {
  527. const measure_bbox = wholeNote?.attrs?.el?.parentElement?.parentElement?.getBoundingClientRect?.() || { x: 0, right: 0 };
  528. let bbox = wholeNote?.attrs?.el?.getBoundingClientRect?.() || { x: 0 };
  529. let stepWidth = Math.abs(measure_bbox.right - bbox.x) / m.numerator;
  530. let stepList: number[] = [];
  531. for (let i = 0; i < m.numerator; i++) {
  532. stepList.push(bbox.x - measure_bbox.x + i * stepWidth);
  533. }
  534. // console.log("🚀 ~ stepList:", stepList, m.measureNumberXML)
  535. return stepList;
  536. }
  537. try {
  538. // 开头是休止符
  539. if (m.measureNumberXML === 1 && wholeNote && wholeNote.isRest()) {
  540. const measure_bbox = wholeNote?.attrs?.el?.parentElement?.parentElement?.getBoundingClientRect?.() || { x: 0, right: 0 };
  541. let bbox = wholeNote?.attrs?.el?.getBoundingClientRect?.() || { x: 0 };
  542. let stepWidth = Math.abs(measure_bbox.right - bbox.x) / m.numerator;
  543. let stepList: any[] = [];
  544. // 第一小节是休止符,节拍指针应该等分宽度
  545. const widthStep = 100 / (m.numerator + 1);
  546. // for (let i = -1; i < m.numerator - 1; i++) {
  547. // stepList.push(bbox.x - measure_bbox.x + i * stepWidth);
  548. // }
  549. // for (let i = 1; i <= m.numerator; i++) {
  550. // stepList.push(widthStep * i + '%');
  551. // }
  552. // console.log(wholeNote?.attrs?.el, m.measureNumberXML)
  553. // console.log("🚀 ~ stepList:", stepList, m.measureNumberXML)
  554. return stepList;
  555. }
  556. } catch (error) {
  557. console.log("🚀 ~ error:", error);
  558. }
  559. return [];
  560. }
  561. // console.log("🚀 ~ arr", [...arr],`小节总时值: ${measureLength}`, clap, m.measureNumberXML);
  562. let totalLength = 0;
  563. let notes: any[] = [];
  564. let stepList: number[] = [];
  565. for (let i = 0; i < arr.length; i++) {
  566. const item = arr[i];
  567. item.index = i;
  568. const noteLength = item._noteLength;
  569. totalLength += noteLength;
  570. // 大于一拍
  571. const exceedStep = Math.floor(totalLength / clap);
  572. // console.log(`note`, item?.svgElement?.attrs?.el,notes.length,{noteLength, exceedStep,clap}, m.measureNumberXML)
  573. if (exceedStep >= 1) {
  574. totalLength -= clap;
  575. // 一拍
  576. let measure_bbox = item?.svgElement?.attrs?.el?.parentElement?.parentElement?.getBoundingClientRect?.() || { x: 0 };
  577. /**
  578. * bug: #9875
  579. * 简谱,渲染有点问题,先使用vf-stave的位置
  580. */
  581. if (state.musicRenderType !== "staff") {
  582. measure_bbox = item?.svgElement?.attrs?.el?.parentElement?.parentElement?.querySelector('.vf-stave')?.getBoundingClientRect?.() || { x: 0 };
  583. }
  584. /**
  585. * 如果measure_bbox不存在(多分轨合并显示可能会出现),则用note再获取一次
  586. */
  587. if (!measure_bbox.width && notes.length > 0) {
  588. measure_bbox = state.musicRenderType !== "staff" ? notes[0]?.svgElement?.attrs?.el?.parentElement?.parentElement?.querySelector('.vf-stave')?.getBoundingClientRect?.() || { x: 0 } :
  589. notes[0]?.svgElement?.attrs?.el?.parentElement?.parentElement?.getBoundingClientRect?.() || { x: 0 }
  590. }
  591. if (notes.length > 0) {
  592. let bbox = notes[0]?.svgElement?.attrs?.el?.getBoundingClientRect?.() || { x: 0 };
  593. let x: any = bbox.x - measure_bbox.x;
  594. if (notes[0]._noteLength / clap >= 1) {
  595. const nextNote = arr[notes[0].index + 1]?.svgElement?.attrs?.el?.getBoundingClientRect?.() || { x: measure_bbox.right } || { x: 0 };
  596. const stepWidth = Math.abs(bbox.x - nextNote.x) / 2;
  597. x = bbox.x - measure_bbox.x + stepWidth;
  598. // console.log(`音符超一拍`, notes[0]?.svgElement?.attrs?.el, arr[notes[0].index + 1]?.svgElement?.attrs?.el, bbox.x - nextNote.x, stepWidth, m.measureNumberXML);
  599. }
  600. // console.log(`一拍`, notes[0]?.svgElement?.attrs?.el, m.measureNumberXML, notes[0]._noteLength , clap, 'aa')
  601. stepList.push(x);
  602. } else {
  603. let bbox = item?.svgElement?.attrs?.el?.getBoundingClientRect?.() || { x: 0 };
  604. let x: any = bbox.x - measure_bbox.x;
  605. // console.log(`一拍`, item?.svgElement?.attrs?.el, m.measureNumberXML)
  606. stepList.push(x);
  607. }
  608. notes = [];
  609. let bbox = item?.svgElement?.attrs?.el?.getBoundingClientRect?.() || { x: 0 };
  610. let x: any = bbox.x - measure_bbox.x;
  611. let stepWidth = 0;
  612. if (exceedStep > 1) {
  613. // 二拍以上
  614. const nextNote = arr[i + 1]?.svgElement?.attrs?.el?.getBoundingClientRect?.() || { x: measure_bbox.right } || { x: 0 };
  615. stepWidth = Math.abs(bbox.x - nextNote.x) / exceedStep;
  616. // console.log("二拍以上 ~ nextNote:",bbox.x , nextNote.x,stepWidth, item?.svgElement?.attrs?.el,arr[i + 1]?.svgElement?.attrs?.el, exceedStep);
  617. }
  618. for (let j = 1; j < exceedStep; j++) {
  619. totalLength -= clap;
  620. // console.log(`超一拍`,item?.svgElement?.attrs?.el, m.measureNumberXML)
  621. stepList.push(x + stepWidth * j);
  622. }
  623. }
  624. //有时值就将音符加入
  625. if (totalLength > Number.EPSILON && totalLength > 0) {
  626. notes.push(item);
  627. }
  628. }
  629. stepList = stepList.reduce((list: any[], n: number) => {
  630. if (list.includes(n)) {
  631. list.push(undefined as any);
  632. } else {
  633. list.push(n);
  634. }
  635. return list;
  636. }, []);
  637. // console.log("stepList", [...stepList], m.measureNumberXML);
  638. return stepList;
  639. }
  640. // 延迟兼容处理
  641. function setCurrentTime(time: number) {
  642. if (browserInfo.huawei || browserInfo.xiaomi) {
  643. time += 0.125;
  644. } else if (browserInfo.android) {
  645. time += 0.11;
  646. } else if (browserInfo.ios) {
  647. time += 0.01;
  648. }
  649. return time;
  650. }
  651. // 自动隐藏光标提示
  652. function hideCursorTip() {
  653. if (!tipsTimer) {
  654. tipsTimer = setTimeout(() => {
  655. metronomeData.cursorTips = ''
  656. clearTimeout(tipsTimer)
  657. tipsTimer = null
  658. }, 2000);
  659. } else {
  660. clearTimeout(tipsTimer)
  661. tipsTimer = setTimeout(() => {
  662. metronomeData.cursorTips = ''
  663. clearTimeout(tipsTimer)
  664. tipsTimer = null
  665. }, 2000);
  666. }
  667. }
  668. function isWithinRange(ranges:any[], index:number) {
  669. for (const range of ranges) {
  670. const start = range[0].measureIndex;
  671. const end = range[1].measureIndex;
  672. if (index >= start && index < end) {
  673. return true;
  674. }
  675. }
  676. return false;
  677. }
  678. export default Metronome;