state.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. import { closeToast, showToast } from "vant";
  2. import { nextTick, reactive } from "vue";
  3. import { OpenSheetMusicDisplay } from "../osmd-extended/src";
  4. import { metronomeData } from "./helpers/metronome";
  5. import { GradualNote, GradualTimes, GradualVersion } from "./type";
  6. import { handleEndEvaluat, handleStartEvaluat } from "./view/evaluating";
  7. import { IFingering, mappingVoicePart, subjectFingering, matchVoicePart } from "/src/view/fingering/fingering-config";
  8. import { handleStartTick } from "./view/tick";
  9. import { audioListStart, getAudioCurrentTime, getAudioDuration, setAudioCurrentTime, setAudioPlaybackRate, audioData } from "./view/audio-list";
  10. import { toggleFollow } from "./view/follow-practice";
  11. import { browser, setStorageSpeed, setGlobalData } from "./utils";
  12. import { api_cloudGetMediaStatus, api_createMusicPlayer, api_cloudChangeSpeed, api_cloudSuspend, api_cloudSetCurrentTime, api_cloudDestroy } from "./helpers/communication";
  13. import { verifyCanRepeat, getDuration } from "./helpers/formateMusic";
  14. import { getMusicSheetDetail } from "./utils/baseApi"
  15. import { getQuery } from "/src/utils/queryString";
  16. import { followData } from "/src/view/follow-practice/index"
  17. const query: any = getQuery();
  18. /** 入门 | 进阶 | 大师 */
  19. export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
  20. /** 渲染类型: 五线谱,简谱 */
  21. export enum EnumMusicRenderType {
  22. /** 五线谱 */
  23. staff = "staff",
  24. /** 简谱 */
  25. firstTone = "firstTone",
  26. /** 固定音高 */
  27. fixedTone = "fixedTone",
  28. }
  29. export const musicscoresettingKey = "musicscoresetting";
  30. /** 有声音的是那个音源 */
  31. export type IPlayState = "music" | "background";
  32. /** 播放状态 */
  33. export type IAudioState = "play" | "paused";
  34. /** 来源 */
  35. export enum IPlatform {
  36. APP = "APP",
  37. PC = "PC",
  38. }
  39. export type ISonges = {
  40. background?: string
  41. music?: string
  42. }
  43. /**
  44. * 特殊教材分类id
  45. */
  46. const classids = [1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,30,31,35,36,38,108,150,151,152,153,154,155,156,157,158,178,179,180,181,182]; // 大雅金唐, 竖笛教程, 声部训练展开的分类ID
  47. // 乐器code码
  48. export const musicalInstrumentCodeInfo = [
  49. {
  50. name: '长笛',
  51. code: 'Flute',
  52. id: 1
  53. },
  54. {
  55. name: '短笛',
  56. code: 'Piccolo',
  57. id: 2
  58. },
  59. {
  60. name: '单簧管',
  61. code: 'Clarinet',
  62. id: 3
  63. },
  64. {
  65. name: '低音单簧管',
  66. code: 'Bass Clarinet',
  67. id: 4
  68. },
  69. {
  70. name: '中音萨克斯',
  71. code: 'Alto Saxophone',
  72. id: 5
  73. },
  74. {
  75. name: '次中音萨克斯',
  76. code: 'Tenor Saxophone',
  77. id: 6
  78. },
  79. {
  80. name: '高音萨克斯',
  81. code: 'Soprano Saxophone',
  82. id: 7
  83. },
  84. {
  85. name: '上低音萨克斯',
  86. code: 'Baritone Saxophone',
  87. id: 8
  88. },
  89. {
  90. name: '双簧管',
  91. code: 'Oboe',
  92. id: 9
  93. },
  94. {
  95. name: '大管',
  96. code: 'Bassoon',
  97. id: 10
  98. },
  99. {
  100. name: '小号',
  101. code: 'Trumpet',
  102. id: 11
  103. },
  104. {
  105. name: '圆号',
  106. code: 'Horn',
  107. id: 12
  108. },
  109. {
  110. name: '长号',
  111. code: 'Trombone',
  112. id: 13
  113. },
  114. {
  115. name: '上低音号',
  116. code: 'Baritone',
  117. id: 14
  118. },
  119. {
  120. name: '次中音号',
  121. code: 'Euphonium',
  122. id: 15
  123. },
  124. {
  125. name: '大号',
  126. code: 'Tuba',
  127. id: 16
  128. },
  129. {
  130. name: '钢琴',
  131. code: 'Piano',
  132. id: 17
  133. },
  134. {
  135. name: '电钢琴',
  136. code: 'Electronical Piano',
  137. id: 18
  138. },
  139. {
  140. name: '钢片琴',
  141. code: 'Glockenspiel',
  142. id: 19
  143. },
  144. {
  145. name: '小提琴',
  146. code: 'Violin',
  147. id: 20
  148. },
  149. {
  150. name: '中提琴',
  151. code: 'Viola',
  152. id: 21
  153. },
  154. {
  155. name: '大提琴',
  156. code: 'Violoncello',
  157. id: 22
  158. },
  159. {
  160. name: '低音提琴',
  161. code: 'Contrabass',
  162. id: 23
  163. },
  164. {
  165. name: '架子鼓',
  166. code: 'Drum Set',
  167. id: 24
  168. },
  169. {
  170. name: '小鼓',
  171. code: 'Snare Drum',
  172. id: 25
  173. },
  174. {
  175. name: '马林巴',
  176. code: 'Marimba',
  177. id: 26
  178. },
  179. {
  180. name: '颤音琴',
  181. code: 'Vibraphone',
  182. id: 27
  183. },
  184. {
  185. name: '钟琴',
  186. code: 'Chimes',
  187. id: 28
  188. },
  189. {
  190. name: '木琴',
  191. code: 'Xylophone',
  192. id: 29
  193. },
  194. {
  195. name: '管钟',
  196. code: 'Tubular Bells',
  197. id: 30
  198. },
  199. {
  200. name: '定音鼓',
  201. code: 'Timpani',
  202. id: 31
  203. },
  204. {
  205. name: '键盘',
  206. code: 'Mallets',
  207. id: 32
  208. },
  209. {
  210. name: '排箫',
  211. code: 'Panpipes',
  212. id: 33
  213. },
  214. {
  215. name: '陶笛',
  216. code: 'Ocarina',
  217. id: 34
  218. },
  219. {
  220. name: '葫芦丝',
  221. code: 'Woodwind',
  222. id: 35
  223. },
  224. {
  225. name: '口风琴',
  226. code: 'Nai',
  227. id: 36
  228. },
  229. {
  230. name: '德式竖笛',
  231. code: 'Tenor Recorder',
  232. id: 37
  233. },
  234. {
  235. name: '英式竖笛',
  236. code: 'Baroque Recorder',
  237. id: 38
  238. },
  239. {
  240. name: '高音陶笛',
  241. code: 'Whistling',
  242. id: 39
  243. },
  244. ]
  245. const state = reactive({
  246. /** 来源 : PC , app */
  247. platform: "" as IPlatform,
  248. appName: "" as "GYM" | "COLEXIU",
  249. musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
  250. /**曲谱是否渲染完成 */
  251. musicRendered: false,
  252. /** 当前曲谱数据ID, 和曲谱ID不一致 */
  253. detailId: "",
  254. /** 曲谱资源URL */
  255. xmlUrl: "",
  256. /** 声部ID */
  257. subjectId: 0 as number,
  258. trackId: 0 as string | number,
  259. /** 分类ID */
  260. categoriesId: 0,
  261. /** 分类名称 */
  262. categoriesName: "",
  263. /** 是否支持评测 */
  264. enableEvaluation: true,
  265. /** 是否支持转谱 */
  266. enableNotation: false,
  267. /** 曲谱ID */
  268. examSongId: "",
  269. /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
  270. cbsExamSongId: "",
  271. /** 曲谱名称 */
  272. examSongName: "",
  273. /** 曲谱封面 */
  274. coverImg: "",
  275. /** 扩展字段 */
  276. extConfigJson: {} as any,
  277. /** 扩展样式字段 */
  278. extStyleConfigJson: {} as any,
  279. /** 是否开启节拍器(mp3节拍器) */
  280. isOpenMetronome: false,
  281. /** 是否显示指法 */
  282. isShowFingering: false,
  283. /** 原音 */
  284. music: "",
  285. /** 伴奏 */
  286. accompany: "",
  287. /** midiURL */
  288. midiUrl: "",
  289. /** 父分ID */
  290. parentCategoriesId: 0,
  291. /** 分类ID */
  292. musicSheetCategoriesId: 0,
  293. /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
  294. bizMusicCategoryId: 0,
  295. /** 资源类型: mp3 | midi */
  296. playMode: "MP3" as "MP3" | "MIDI",
  297. /** 设置的速度 */
  298. speed: 0,
  299. /** 曲谱音频正常的速度 */
  300. originSpeed: 0,
  301. /** 播放过程中显示的速度 */
  302. playIngSpeed: 0,
  303. /** 分轨名称 */
  304. track: "",
  305. /** 当前显示声部索引 */
  306. partIndex: 0,
  307. /** 是否需要节拍器 */
  308. needTick: false,
  309. /** 曲谱实例 */
  310. osmd: null as unknown as OpenSheetMusicDisplay,
  311. /**是否是特殊乐谱类型, 主要针对管乐迷 */
  312. isSpecialBookCategory: false,
  313. /** 播放状态 */
  314. playState: "paused" as IAudioState,
  315. /** 播放结束状态 */
  316. playEnd: false,
  317. /** 播放那个: 原音,伴奏 */
  318. playSource: "music" as IPlayState,
  319. /** 播放进度 */
  320. playProgress: 0,
  321. /** 激活的note index */
  322. activeNoteIndex: 0,
  323. /** 激活的小节 */
  324. activeMeasureIndex: 0,
  325. /** 选段状态 */
  326. sectionStatus: false,
  327. /** 选段数据 */
  328. section: [] as any[],
  329. /** 选段背景 */
  330. sectionBoundingBoxs: [] as any[],
  331. /** 开启选段预备 */
  332. isOpenPrepare: false,
  333. /** 选段预备 */
  334. sectionFirst: null as any,
  335. /** 音符数据 */
  336. times: [] as any[],
  337. /** 播放模式 */
  338. modeType: "practise" as "practise" | "follow" | "evaluating",
  339. /** 设置 */
  340. setting: {
  341. /** 效音提醒 */
  342. soundEffect: true,
  343. /** 护眼模式 */
  344. eyeProtection: false,
  345. /** 摄像头 */
  346. camera: false,
  347. /** 摄像头透明度 */
  348. cameraOpacity: 70,
  349. /** 循环播放 */
  350. repeatAutoPlay: true,
  351. /** 显示指法 */
  352. displayFingering: true,
  353. /** 显示光标 */
  354. displayCursor: true,
  355. /** 频率 */
  356. frequency: 0,
  357. /** 评测难度 */
  358. evaluationDifficulty: "BEGINNER" as IDifficulty,
  359. /** 保存到相册 */
  360. saveToAlbum: true,
  361. /** 开启伴奏 */
  362. enableAccompaniment: true,
  363. /** 反应时间 */
  364. reactionTimeMs: 0,
  365. /** 节拍器音量 */
  366. beatVolume: 50,
  367. },
  368. /** 后台设置的基准评测频率 */
  369. baseFrequency: 440,
  370. /** mp3节拍器的时间,统计拍数、速度计算得出 */
  371. fixtime: 0,
  372. /** 指法信息 */
  373. fingeringInfo: {} as IFingering,
  374. /** 滚动容器的ID */
  375. scrollContainer: "musicAndSelection",
  376. /** 是否是打击乐 */
  377. isPercussion: false,
  378. /** 评测标准 */
  379. evaluationStandard: '',
  380. /** 是否重复节拍器的时间 */
  381. repeatedBeats: 0,
  382. /**当前曲谱中所有声部名字 */
  383. partListNames: [] as any,
  384. /** 渐变速度信息 */
  385. gradual: [] as GradualNote[],
  386. /** 渐变速度版本 */
  387. gradualVersion: GradualVersion.BASE as GradualVersion,
  388. /** 渐变时间信息 */
  389. gradualTimes: null as GradualTimes,
  390. /** 单声部多声轨 */
  391. multitrack: 0,
  392. /** 缩放 */
  393. zoom: 0.8,
  394. /** 渲染曲谱比例 */
  395. musicZoom: 1,
  396. /** 练习,评测是否是选段模式 */
  397. isSelectMeasureMode: false,
  398. /** 是否是评分显示 */
  399. isReport: false,
  400. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  401. isHideEvaluatReportSaveBtn: false,
  402. /** 是否是合奏 */
  403. isConcert: false,
  404. /** 用户选择的结束小节数 */
  405. userChooseEndIndex: 0,
  406. /** 重播小节集合信息 */
  407. repeatInfo: [] as any,
  408. /** 多分轨的曲子,可支持筛选的分轨 */
  409. canSelectTracks: [] as any,
  410. /** 声部codeId */
  411. subjectCodeId: 0 as number,
  412. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  413. musicalCodeId: 0 as number,
  414. /** 乐器code,用于评测传参 */
  415. musicalCode: '' as any,
  416. /** 合奏曲目是否合并展示 */
  417. isCombineRender: false,
  418. /** 小节的持续时长,以后台设置的播放速度计算 */
  419. measureTime: 0,
  420. /** 跟练模式,节拍器播放的时间 */
  421. beatStartTime: 0,
  422. /** 是否为详情预览模式 */
  423. isPreView: false,
  424. /** 是否为评测报告模式 */
  425. isEvaluatReport: false,
  426. /** midi播放器是否初始化中 */
  427. midiPlayIniting: false,
  428. /** 曲目信息 */
  429. songs: {} as ISonges,
  430. isAppPlay: false, // 是否midi音频,midi是app播放
  431. /** 音频播放器实例 */
  432. audiosInstance: null as any,
  433. /** midi音频的时长 */
  434. durationNum: 0,
  435. midiSectionStart: 0,
  436. /** 音频文件是否加载完成 */
  437. audioDone: false,
  438. /** 谱面svgdom节点 */
  439. osmdSvgDom: null as any,
  440. });
  441. const browserInfo = browser();
  442. let offset_duration = 0;
  443. /** 自定义数据 */
  444. export const customData = reactive({
  445. /** 自定义音符时值 */
  446. customNoteRealValue: [] as any,
  447. /** 自定义音符按读取到的时值 */
  448. customNoteCurrentTime: false,
  449. });
  450. /** 在渲染前后计算光标应该走到的音符 */
  451. const setStep = () => {
  452. // console.log('播放状态',state.playState)
  453. if (state.playState !== "play") {
  454. console.log("暂停播放");
  455. return;
  456. }
  457. let startTime = Date.now();
  458. requestAnimationFrame(() => {
  459. const endTime = Date.now();
  460. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  461. if (endTime - startTime < 16.7) {
  462. handlePlaying();
  463. setStep();
  464. } else {
  465. setTimeout(() => {
  466. handlePlaying();
  467. setStep();
  468. }, 16.7);
  469. }
  470. });
  471. };
  472. /** 开始播放 */
  473. export const onPlay = () => {
  474. console.log("开始播放");
  475. state.playEnd = false;
  476. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  477. offset_duration = 0.2;
  478. setStep();
  479. };
  480. /** 播放模式结束自动重播 */
  481. const autoResetPlay = () => {
  482. if (state.modeType !== "practise") return;
  483. skipNotePlay(0, true);
  484. // 没有开启自动重播, 不是练习模式
  485. if (!state.setting.repeatAutoPlay) return;
  486. scrollViewNote();
  487. setTimeout(() => {
  488. togglePlay("play");
  489. }, 1000);
  490. };
  491. /** 播放完成事件 */
  492. export const onEnded = () => {
  493. console.log("音频播放结束");
  494. // if (state.isAppPlay) {
  495. // // 销毁播放器
  496. // api_cloudDestroy();
  497. // }
  498. // 修改状态为结束
  499. state.playEnd = true;
  500. state.playState = "paused";
  501. // 结束播放
  502. audioListStart(state.playState);
  503. // 调用结束评测
  504. handleEndEvaluat(true);
  505. // 调用自动重复播放
  506. autoResetPlay();
  507. };
  508. /**
  509. * 播放一直触发的事件
  510. */
  511. const handlePlaying = () => {
  512. const currentTime = getAudioCurrentTime();
  513. const duration = getAudioDuration();
  514. state.playProgress = (currentTime / duration) * 100;
  515. let item = getNote(currentTime);
  516. // console.log(11111,currentTime,duration,state.playSource, item.i)
  517. // console.log(item.i,item.noteId,item.measureSpeed)
  518. // 练习模式下,实时刷新小节速度
  519. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  520. const ratio = state.speed / state.originSpeed
  521. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  522. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  523. state.playIngSpeed = state.speed
  524. }
  525. if (item) {
  526. // 选段状态下
  527. if (state.sectionStatus && state.section.length === 2) {
  528. // 如果开启了预备拍
  529. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  530. const selectEndItem = state.section[1];
  531. /**
  532. * #9374,反复小节的曲目播放错误, bug修复
  533. * 曲目:噢!苏珊娜-排箫-人音
  534. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  535. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  536. */
  537. if (state.repeatInfo.length) {
  538. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  539. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  540. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  541. const preItem = state.times[item.i - 1]
  542. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  543. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  544. if (skipItem) {
  545. // 跳转到指定的音频位置
  546. setAudioCurrentTime(skipItem.time, skipItem.i);
  547. gotoNext(skipItem);
  548. return
  549. }
  550. }
  551. }
  552. }
  553. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  554. // if (currentTime - selectEndItem.endtime > offset_duration) {
  555. //console.log(currentTime,selectEndItem.endtime)
  556. if (currentTime - selectEndItem.endtime >= 0) {
  557. console.log("选段播放结束",state.setting.repeatAutoPlay);
  558. // 如果为选段评测模式
  559. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  560. onEnded();
  561. return;
  562. }
  563. // #8698 bug修复
  564. if (state.modeType === "practise" && state.sectionStatus) {
  565. onEnded();
  566. resetPlaybackToStart();
  567. return;
  568. }
  569. item = selectStartItem;
  570. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  571. }
  572. }
  573. gotoNext(item);
  574. }
  575. // 评测不播放叮咚节拍器
  576. // if (state.modeType !== "evaluating") {
  577. // metronomeData.metro?.sound(currentTime);
  578. // }
  579. metronomeData.metro?.sound(currentTime);
  580. };
  581. /** 跳转到指定音符开始播放 */
  582. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  583. const item = state.times[itemIndex];
  584. let itemTime = item.time;
  585. if (isStart) {
  586. itemTime = 0;
  587. }
  588. if (item) {
  589. setAudioCurrentTime(itemTime, itemIndex);
  590. gotoNext(item);
  591. metronomeData.metro?.sound(itemTime);
  592. if (state.isAppPlay) {
  593. await api_cloudSetCurrentTime({
  594. currentTime: itemTime * 1000,
  595. songID: state.examSongId,
  596. })
  597. audioData.progress = itemTime
  598. state.midiSectionStart = itemTime
  599. }
  600. }
  601. };
  602. /**
  603. * 切换曲谱播放状态
  604. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  605. */
  606. export const togglePlay = async (playState?: "play" | "paused") => {
  607. // 如果mp3资源还在加载中,给出提示
  608. if (!state.isAppPlay && !state.audioDone) {
  609. showToast('音频资源加载中,请稍后')
  610. return
  611. }
  612. // midi播放
  613. if (state.isAppPlay) {
  614. if( playState === "paused" ) {
  615. await api_cloudSuspend({
  616. songID: state.examSongId,
  617. })
  618. state.playState = 'paused'
  619. return
  620. }
  621. skipNotePlay(state.activeNoteIndex, false);
  622. await api_cloudChangeSpeed({
  623. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  624. originalSpeed: state.originSpeed,
  625. songID: state.examSongId,
  626. });
  627. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  628. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  629. state.playState = status
  630. } else {
  631. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  632. }
  633. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  634. resetPlaybackToStart();
  635. }
  636. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  637. if (state.playState === "play" && state.needTick) {
  638. const tickend = await handleStartTick();
  639. // console.log("🚀 ~ tickend:", tickend)
  640. // 节拍器返回false, 取消播放
  641. if (!tickend) {
  642. state.playState = "paused";
  643. return false;
  644. }
  645. }
  646. // 如果选段没有结束, 直接开始播放,清空选段状态
  647. if (state.playState == "play") {
  648. if (state.sectionStatus && state.section.length < 2) {
  649. clearSelection();
  650. }
  651. }
  652. audioListStart(state.playState);
  653. return true;
  654. };
  655. /** 结束播放 */
  656. export const handleStopPlay = () => {
  657. state.playState = "paused";
  658. audioListStart(state.playState);
  659. };
  660. /** 重置播放为开始 */
  661. export const resetPlaybackToStart = () => {
  662. // 如果为选段状态
  663. if (state.sectionStatus && state.section.length === 2) {
  664. state.section = formateSelectMearure(state.section);
  665. return;
  666. } else {
  667. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  668. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  669. }
  670. skipNotePlay(0, true);
  671. };
  672. /** 跳转到指定音符 */
  673. export const gotoCustomNote = (index: number) => {
  674. try {
  675. state.osmd.cursor.reset();
  676. } catch (error) {}
  677. for (let i = 0; i < index; i++) {
  678. state.osmd.cursor.next();
  679. }
  680. };
  681. const setCursorPosition = (note: any, cursor: any) => {
  682. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  683. /**
  684. * bug:#9920、#9940
  685. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  686. */
  687. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  688. return
  689. }
  690. nextTick(() => {
  691. let bbox = note.bbox;
  692. if (!bbox) {
  693. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  694. x: 0,
  695. y: 0,
  696. };
  697. const parentLeft = musicContainer.x || 0;
  698. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  699. if (noteEle) {
  700. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  701. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  702. if (noteHeadBbox) {
  703. note.bbox = {
  704. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  705. width: noteHeadBbox.width * 1.5,
  706. };
  707. bbox = note.bbox;
  708. }
  709. }
  710. }
  711. if (!bbox) return;
  712. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  713. const width = (bbox.width - baseW) / 3;
  714. // console.log(555555,bbox.left,width)
  715. cursor.cursorElement.style.left = bbox.left + "px";
  716. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  717. });
  718. }
  719. };
  720. /** 跳转到下一个音符 */
  721. export const gotoNext = (note: any) => {
  722. // console.log(33333333333,state.activeNoteIndex,note.i)
  723. const num = note.i;
  724. if (state.activeNoteIndex === note.i) {
  725. try {
  726. setCursorPosition(note, state.osmd.cursor);
  727. } catch (error) {
  728. console.log(error);
  729. }
  730. return;
  731. }
  732. const osmd = state.osmd;
  733. let prev = state.activeNoteIndex;
  734. state.activeNoteIndex = num;
  735. state.activeMeasureIndex = note.MeasureNumberXML;
  736. if (prev && num - prev === 1) {
  737. osmd.cursor.next();
  738. } else if (prev && num - prev > 0) {
  739. while (num - prev > 0) {
  740. prev++;
  741. osmd.cursor.next();
  742. }
  743. } else {
  744. gotoCustomNote(num);
  745. }
  746. try {
  747. setCursorPosition(note, state.osmd.cursor);
  748. } catch (error) {
  749. console.log(error);
  750. }
  751. scrollViewNote();
  752. };
  753. /** 获取指定音符 */
  754. export const getNote = (currentTime: number) => {
  755. const times = state.times;
  756. const len = state.times.length;
  757. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  758. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  759. onEnded();
  760. return;
  761. }
  762. let _item = null as any;
  763. for (let i = state.activeNoteIndex; i < len; i++) {
  764. const item = times[i];
  765. const prevItem = times[i - 1];
  766. if (currentTime >= item.time) {
  767. if (!prevItem || item.time != prevItem.time) {
  768. _item = item;
  769. }
  770. } else {
  771. break;
  772. }
  773. }
  774. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  775. return _item;
  776. };
  777. /** 重播 */
  778. export const handleResetPlay = () => {
  779. // 如果是midi需要重置播放进度
  780. if (state.isAppPlay) {
  781. audioData.progress = 0
  782. }
  783. resetPlaybackToStart();
  784. // 如果是暂停, 直接播放
  785. togglePlay("play");
  786. };
  787. /** 设置速度 */
  788. export const handleSetSpeed = (speed: number) => {
  789. setStorageSpeed(state.examSongId, speed);
  790. state.speed = speed;
  791. };
  792. /** 清除选段状态 */
  793. export const clearSelection = () => {
  794. state.sectionStatus = false;
  795. state.section = [];
  796. closeToast();
  797. };
  798. /** 开启选段 */
  799. export const handleChangeSection = () => {
  800. // 如果开启了选段,再次点击取消选段
  801. if (state.sectionStatus) {
  802. togglePlay("paused");
  803. clearSelection();
  804. skipNotePlay(0, true);
  805. state.sectionFirst = null;
  806. return;
  807. }
  808. state.sectionStatus = true;
  809. // 开启
  810. if (state.sectionStatus) {
  811. togglePlay("paused");
  812. }
  813. showToast({
  814. message: "请选择开始小节",
  815. duration: 0,
  816. position: "top",
  817. className: "selectionToast",
  818. });
  819. };
  820. /** 效验并格式化选段小节 */
  821. const formateSelectMearure = (_list: any[]): any[] => {
  822. if (!_list.length) return [];
  823. const list = _list.sort((a, b) => a.time - b.time);
  824. const startXml = list[0]?.measureOpenIndex;
  825. const endXml = list.last()?.measureOpenIndex;
  826. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  827. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  828. // 没有找到选段小节
  829. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  830. clearSelection();
  831. return [];
  832. }
  833. list[0] = selectStartMeasure[0];
  834. list[1] = selectEndMeasure.last();
  835. let startItemINdex = list[0].i;
  836. // 开启预备拍
  837. if (state.isOpenPrepare) {
  838. const startXmlIndex = list[0].MeasureNumberXML;
  839. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  840. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  841. }
  842. skipNotePlay(startItemINdex, startItemINdex === 0);
  843. return list;
  844. };
  845. /** 选择选段 */
  846. export const handleSelection = (item: any) => {
  847. if (!state.sectionStatus || state.section.length > 1) return;
  848. if (state.section.length !== 2 && item) {
  849. state.section.push(item);
  850. if (state.section.length === 2) {
  851. setSection(state.section[0].MeasureNumberXML,state.section[1].MeasureNumberXML)
  852. //state.section = formateSelectMearure(state.section);
  853. closeToast();
  854. }
  855. }
  856. if (state.section.length === 1) {
  857. showToast({
  858. message: "请选择结束小节",
  859. duration: 0,
  860. position: "top",
  861. className: "selectionToast",
  862. });
  863. }
  864. };
  865. /** 阶段练习、阶段评测设置选段小节 */
  866. export const setSection = (start: number, end: number, userSpeed?: number) => {
  867. const startNotes = state.times.filter(
  868. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  869. )
  870. const endNotes = state.times.filter(
  871. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  872. )
  873. state.userChooseEndIndex = end
  874. const lastEndId = endNotes[endNotes.length - 1].noteId
  875. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  876. // 是否符合重播规则
  877. const canRepeatInfo = verifyCanRepeat(start, end)
  878. console.log('能否重播',canRepeatInfo)
  879. const isCanRepeat = canRepeatInfo.canRepeat
  880. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  881. /**
  882. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  883. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  884. * TODO:通过vf-volta判断是否是跳房子
  885. */
  886. let isSkipVolta = false; // 结束小节是否是跳房子小节
  887. if (lastEndNotes.length === 1) {
  888. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  889. }
  890. let currentEndNum: number = end
  891. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  892. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  893. currentEndNum = currentEndNum - 1
  894. const newEndNotes = state.times.filter(
  895. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  896. )
  897. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  898. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  899. }
  900. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  901. const startNote = startNotes[0]
  902. // const endNote = endNotes[endNotes.length - 1]
  903. const endNote = lastEndNotes[endIdx]
  904. if (startNote && endNote) {
  905. state.isSelectMeasureMode = true;
  906. // 设置小节
  907. hanldeDirectSelection([startNote, endNote]);
  908. //设置速度
  909. if (userSpeed) {
  910. handleSetSpeed(userSpeed);
  911. }
  912. }
  913. }
  914. /** 直接设置选段 */
  915. export const hanldeDirectSelection = (list: any[]) => {
  916. if (!Array.isArray(list) || list.length !== 2) return;
  917. state.sectionStatus = true;
  918. setTimeout(() => {
  919. state.section = formateSelectMearure(list);
  920. console.log('选段小节',state.section)
  921. }, 500);
  922. };
  923. let offsetTop = 0;
  924. /**
  925. * 窗口内滚动到音符的区域
  926. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  927. * @returns void
  928. */
  929. export const scrollViewNote = () => {
  930. const cursorElement = document.getElementById("cursorImg-0")!;
  931. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  932. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  933. offsetTop = cursorElement.offsetTop;
  934. if (offsetTop > 50) {
  935. musicAndSelection.scrollTo({
  936. top: (offsetTop - 50) * state.musicZoom,
  937. behavior: "smooth",
  938. });
  939. } else {
  940. musicAndSelection.scrollTo({
  941. top: 0,
  942. behavior: "smooth",
  943. });
  944. }
  945. };
  946. /** 检测是否是节奏练习 */
  947. export const isRhythmicExercises = () => {
  948. return state.examSongName.indexOf("节奏练习") > -1;
  949. };
  950. /** 重置状态 */
  951. export const handleRessetState = () => {
  952. // 切换模式,清除选段
  953. clearSelection();
  954. skipNotePlay(0, true);
  955. // midi 重置播放进度
  956. if (state.isAppPlay) {
  957. audioData.progress = 0;
  958. }
  959. if (state.modeType === "evaluating") {
  960. handleStartEvaluat();
  961. } else if (state.modeType === "practise") {
  962. togglePlay("paused");
  963. } else if (state.modeType === "follow") {
  964. toggleFollow(false);
  965. }
  966. };
  967. export default state;
  968. /** 初始化评测音频 */
  969. export const evaluatCreateMusicPlayer = () => {
  970. return api_createMusicPlayer({
  971. musicSrc: state.accompany || state.music, // 曲谱音频url
  972. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  973. });
  974. };
  975. /** 获取内容平台的接口详情并初始化state信息 */
  976. export const getMusicDetail = async (id: string) => {
  977. const res = await getMusicSheetDetail(id);
  978. if (res?.code === 200) {
  979. getMusicInfo(res)
  980. }
  981. };
  982. const getMusicInfo = (res: any) => {
  983. const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
  984. // 原音声轨
  985. const musicData = res.data.musicSheetSoundList?.[index] || {};
  986. // 伴奏声轨
  987. const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
  988. const musicInfo = {
  989. ...res.data,
  990. music: musicData.audioFileUrl || '',
  991. accompany: accompanyData.audioFileUrl || '',
  992. musicSheetId: musicData.musicSheetId || res.data.bizId,
  993. track: musicData.track || '',
  994. };
  995. console.log("🚀 ~ musicInfo:", musicInfo);
  996. setState(musicInfo, index);
  997. };
  998. const setState = (data: any, index: number) => {
  999. state.appName = "COLEXIU";
  1000. state.detailId = data.bizId;
  1001. state.xmlUrl = data.xmlFileUrl;
  1002. state.partIndex = index;
  1003. state.trackId = data.track;
  1004. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1005. // 声部code
  1006. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1007. // 乐器code
  1008. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1009. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1010. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1011. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1012. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1013. state.categoriesId = data.musicCategoryId;
  1014. state.categoriesName = data.musicTagNames;
  1015. // state.enableEvaluation = data.isEvaluated ? true : false;
  1016. state.examSongId = data.bizId + "";
  1017. state.cbsExamSongId = data.id + "";
  1018. state.examSongName = data.name;
  1019. state.coverImg = data.musicCover ?? "";
  1020. // 单声部多声轨合并展示
  1021. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1022. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1023. // 解析扩展字段
  1024. if (data.extConfigJson) {
  1025. try {
  1026. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1027. } catch (error) {
  1028. console.error("解析扩展字段错误:", error);
  1029. }
  1030. }
  1031. state.gradualTimes = state.extConfigJson.gradualTimes;
  1032. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1033. // 曲子包含节拍器,就不开启节拍器
  1034. state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
  1035. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1036. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1037. state.isShowFingering = data.isShowFingering ? true : false;
  1038. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1039. state.isAppPlay = data.playMode === 'MIDI';
  1040. state.music = data.music;
  1041. state.accompany = data.accompany;
  1042. state.midiUrl = data.midiFileUrl;
  1043. state.parentCategoriesId = data.musicTag;
  1044. state.musicSheetCategoriesId = data.musicCategoryId;
  1045. state.bizMusicCategoryId = data.bizMusicCategoryId
  1046. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1047. state.originSpeed = state.speed = data.playSpeed;
  1048. // state.playIngSpeed = data.playSpeed;
  1049. const track = data.code || data.track;
  1050. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1051. // 能否评测,根据当前声轨有无伴奏判断
  1052. if (state.isAppPlay) {
  1053. state.enableEvaluation = state.midiUrl ? true : false
  1054. } else {
  1055. state.enableEvaluation = state.accompany ? true : false
  1056. }
  1057. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1058. // multiTracksSelection 返回为空,默认代表全部分轨
  1059. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1060. // 开启预备小节
  1061. state.isOpenPrepare = true;
  1062. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1063. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1064. // 是否打击乐
  1065. /**
  1066. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1067. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1068. * 打击乐&节奏练习,没有跟练模式
  1069. */
  1070. // state.isPercussion = isRhythmicExercises();
  1071. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1072. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1073. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1074. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1075. // 设置指法
  1076. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1077. /**
  1078. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1079. * 获取指法code
  1080. */
  1081. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1082. state.fingeringInfo = subjectFingering(code);
  1083. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1084. state.musicalCodeId = state.fingeringInfo?.id || 0
  1085. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1086. ;(window as any).DYSubjectId = state.musicalCodeId
  1087. // 开启自定义每行显示的小节数
  1088. ;(window as any).customSectionAmount = true
  1089. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1090. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1091. state.setting.displayFingering = false
  1092. }
  1093. // 检测是否原音和伴奏都有
  1094. if (!state.music || !state.accompany) {
  1095. state.playSource = state.music ? "music" : "background";
  1096. }
  1097. // 如果是PC端,放大曲谱
  1098. state.platform = query.platform?.toLocaleUpperCase() || "";
  1099. if (state.platform === IPlatform.PC) {
  1100. state.zoom = query.zoom || 1.5;
  1101. }
  1102. /**
  1103. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1104. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1105. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1106. *
  1107. */
  1108. let pitchTrack = null
  1109. if (state.isConcert) {
  1110. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1111. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1112. } else {
  1113. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1114. }
  1115. let musicalRenderType = ''
  1116. if (pitchTrack?.defaultScore) {
  1117. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1118. }
  1119. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1120. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1121. console.log("state对象", state);
  1122. // 评测基准频率
  1123. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1124. state.baseFrequency = Number(state.baseFrequency)
  1125. // 用户上次的频率和基准频率误差超过10,则重置
  1126. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1127. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1128. } else {
  1129. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1130. }
  1131. };
  1132. // 多分轨合并显示标示
  1133. const setCustom = (trackNum?: number) => {
  1134. if (trackNum || state.extConfigJson.multitrack) {
  1135. state.multitrack = trackNum || 0
  1136. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1137. }
  1138. };
  1139. /** 跟练模式播放节拍器(叮咚) */
  1140. export const followBeatPaly = () => {
  1141. let metroTimer: any = null;
  1142. if (!followData.start) {
  1143. clearTimeout(metroTimer)
  1144. metroTimer = null
  1145. return;
  1146. }
  1147. const time = state.measureTime*1000 / metronomeData.totalNumerator
  1148. requestAnimationFrame(() => {
  1149. const endTime = Date.now();
  1150. if (endTime - state.beatStartTime < time) {
  1151. followBeatPaly();
  1152. } else {
  1153. // metroTimer = setTimeout(() => {
  1154. // metronomeData.metro?.simulatePlayAudio()
  1155. // startTime = Date.now();
  1156. // followBeatPaly();
  1157. // }, time);
  1158. metronomeData.metro?.simulatePlayAudio()
  1159. state.beatStartTime = Date.now();
  1160. followBeatPaly();
  1161. }
  1162. });
  1163. };
  1164. // let moveX = 0;
  1165. // /** 移动svgdom */
  1166. // export const moveSvgDom = (offset: number) => {
  1167. // moveX += offset;
  1168. // state.osmdSvgDom.style.transform = `translateX(${moveX}px)`;
  1169. // }