state.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
  371. fixtime: 0,
  372. /** evxml等待播放的时间 */
  373. evXmlBeginTime: 0,
  374. /** 指法信息 */
  375. fingeringInfo: {} as IFingering,
  376. /** 滚动容器的ID */
  377. scrollContainer: "musicAndSelection",
  378. /** 是否是打击乐 */
  379. isPercussion: false,
  380. /** 评测标准 */
  381. evaluationStandard: '',
  382. /** 是否重复节拍器的时间 */
  383. repeatedBeats: 0,
  384. /**当前曲谱中所有声部名字 */
  385. partListNames: [] as any,
  386. /** 渐变速度信息 */
  387. gradual: [] as GradualNote[],
  388. /** 渐变速度版本 */
  389. gradualVersion: GradualVersion.BASE as GradualVersion,
  390. /** 渐变时间信息 */
  391. gradualTimes: null as GradualTimes,
  392. /** 单声部多声轨 */
  393. multitrack: 0,
  394. /** 缩放 */
  395. zoom: 0.8,
  396. /** 渲染曲谱比例 */
  397. musicZoom: 1,
  398. /** 练习,评测是否是选段模式 */
  399. isSelectMeasureMode: false,
  400. /** 是否是评分显示 */
  401. isReport: false,
  402. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  403. isHideEvaluatReportSaveBtn: false,
  404. /** 是否是合奏 */
  405. isConcert: false,
  406. /** 用户选择的结束小节数 */
  407. userChooseEndIndex: 0,
  408. /** 重播小节集合信息 */
  409. repeatInfo: [] as any,
  410. /** 多分轨的曲子,可支持筛选的分轨 */
  411. canSelectTracks: [] as any,
  412. /** 声部codeId */
  413. subjectCodeId: 0 as number,
  414. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  415. musicalCodeId: 0 as number,
  416. /** 乐器code,用于评测传参 */
  417. musicalCode: '' as any,
  418. /** 合奏曲目是否合并展示 */
  419. isCombineRender: false,
  420. /** 小节的持续时长,以后台设置的播放速度计算 */
  421. measureTime: 0,
  422. /** 跟练模式,节拍器播放的时间 */
  423. beatStartTime: 0,
  424. /** 是否为详情预览模式 */
  425. isPreView: false,
  426. /** 是否为评测报告模式 */
  427. isEvaluatReport: false,
  428. /** midi播放器是否初始化中 */
  429. midiPlayIniting: false,
  430. /** 曲目信息 */
  431. songs: {} as ISonges,
  432. isAppPlay: false, // 是否midi音频,midi是app播放
  433. /** 音频播放器实例 */
  434. audiosInstance: null as any,
  435. /** midi音频的时长 */
  436. durationNum: 0,
  437. midiSectionStart: 0,
  438. /** 音频文件是否加载完成 */
  439. audioDone: false,
  440. /** 谱面svgdom节点 */
  441. osmdSvgDom: null as any,
  442. /** 滚动容器dom */
  443. osdmScrollDom: null as any,
  444. /** 光标dom */
  445. cursorDom: null as any,
  446. fistNoteLeft: 0,
  447. /** 是否为单行谱渲染模式 */
  448. isSingleLine: false,
  449. /** 首尾音符的间距 */
  450. noteDistance: 0,
  451. /** 一行谱运动模式,平滑移动、匀速移动 */
  452. moveType: "smooth" as "smooth" | "uniform",
  453. /** 是否是evxml */
  454. isEvxml: false,
  455. noTimes: [] as any,
  456. attendHideMenu: true,
  457. /** 老师端:功能按钮布局方向 */
  458. playBtnDirection: "left" as "left" | "right",
  459. /** 云教练按钮方向,如果有指法并且是竖向的指法,为了防止播放按钮把指法挡住,此时云教练播放按钮方向应该取反 */
  460. musicScoreBtnDirection: "right" as "left" | "right",
  461. /** 是否在老师端上课页面 */
  462. isAttendClass: false,
  463. /** 引导页信息 */
  464. guideInfo: null as any,
  465. });
  466. const browserInfo = browser();
  467. let offset_duration = 0;
  468. /** 自定义数据 */
  469. export const customData = reactive({
  470. /** 自定义音符时值 */
  471. customNoteRealValue: [] as any,
  472. /** 自定义音符按读取到的时值 */
  473. customNoteCurrentTime: false,
  474. });
  475. /** 在渲染前后计算光标应该走到的音符 */
  476. const setStep = () => {
  477. // console.log('播放状态',state.playState)
  478. if (state.playState !== "play") {
  479. console.log("暂停播放");
  480. return;
  481. }
  482. let startTime = Date.now();
  483. requestAnimationFrame(() => {
  484. const endTime = Date.now();
  485. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  486. if (endTime - startTime < 16.7) {
  487. handlePlaying();
  488. setStep();
  489. } else {
  490. setTimeout(() => {
  491. handlePlaying();
  492. setStep();
  493. }, 16.7);
  494. }
  495. });
  496. };
  497. /** 开始播放 */
  498. export const onPlay = () => {
  499. console.log("开始播放");
  500. state.playEnd = false;
  501. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  502. offset_duration = 0.2;
  503. setStep();
  504. };
  505. /** 播放模式结束自动重播 */
  506. const autoResetPlay = () => {
  507. if (state.modeType !== "practise") return;
  508. skipNotePlay(0, true);
  509. // 没有开启自动重播, 不是练习模式
  510. if (!state.setting.repeatAutoPlay) return;
  511. scrollViewNote();
  512. setTimeout(() => {
  513. togglePlay("play");
  514. }, 1000);
  515. };
  516. /** 播放完成事件 */
  517. export const onEnded = () => {
  518. console.log("音频播放结束");
  519. // if (state.isAppPlay) {
  520. // // 销毁播放器
  521. // api_cloudDestroy();
  522. // }
  523. // 修改状态为结束
  524. state.playEnd = true;
  525. state.playState = "paused";
  526. // 结束播放
  527. audioListStart(state.playState);
  528. // 调用结束评测
  529. handleEndEvaluat(true);
  530. // 调用自动重复播放
  531. autoResetPlay();
  532. };
  533. /**
  534. * 播放一直触发的事件
  535. */
  536. const handlePlaying = () => {
  537. const currentTime = getAudioCurrentTime();
  538. const duration = getAudioDuration();
  539. state.playProgress = (currentTime / duration) * 100;
  540. let item = getNote(currentTime);
  541. // console.log(11111,currentTime,duration,state.playSource, item)
  542. // console.log(item.i,item.noteId,item.measureSpeed)
  543. // 练习模式下,实时刷新小节速度
  544. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  545. const ratio = state.speed / state.originSpeed
  546. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  547. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  548. state.playIngSpeed = state.speed
  549. }
  550. if (item) {
  551. // 选段状态下
  552. if (state.sectionStatus && state.section.length === 2) {
  553. // 如果开启了预备拍
  554. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  555. const selectEndItem = state.section[1];
  556. /**
  557. * #9374,反复小节的曲目播放错误, bug修复
  558. * 曲目:噢!苏珊娜-排箫-人音
  559. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  560. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  561. */
  562. if (state.repeatInfo.length) {
  563. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  564. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  565. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  566. const preItem = state.times[item.i - 1]
  567. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  568. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  569. if (skipItem) {
  570. // 跳转到指定的音频位置
  571. setAudioCurrentTime(skipItem.time, skipItem.i);
  572. gotoNext(skipItem);
  573. return
  574. }
  575. }
  576. }
  577. }
  578. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  579. // if (currentTime - selectEndItem.endtime > offset_duration) {
  580. //console.log(currentTime,selectEndItem.endtime)
  581. if (currentTime - selectEndItem.endtime >= 0) {
  582. console.log("选段播放结束",state.setting.repeatAutoPlay);
  583. // 如果为选段评测模式
  584. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  585. onEnded();
  586. return;
  587. }
  588. // #8698 bug修复
  589. if (state.modeType === "practise" && state.sectionStatus) {
  590. onEnded();
  591. resetPlaybackToStart();
  592. return;
  593. }
  594. item = selectStartItem;
  595. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  596. }
  597. }
  598. gotoNext(item);
  599. }
  600. // 评测不播放叮咚节拍器
  601. // if (state.modeType !== "evaluating") {
  602. // metronomeData.metro?.sound(currentTime);
  603. // }
  604. metronomeData.metro?.sound(currentTime);
  605. // 一行谱,需要滚动小节
  606. if (state.isSingleLine) {
  607. if (state.moveType === 'smooth') {
  608. smoothMoveSvgDom();
  609. } else {
  610. uniformMoveSvgDom();
  611. }
  612. }
  613. };
  614. /** 跳转到指定音符开始播放 */
  615. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  616. const item = state.times[itemIndex];
  617. let itemTime = item.time;
  618. if (isStart) {
  619. itemTime = 0;
  620. }
  621. if (item) {
  622. setAudioCurrentTime(itemTime, itemIndex);
  623. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  624. gotoNext(item, true);
  625. metronomeData.metro?.sound(itemTime);
  626. if (state.isAppPlay) {
  627. await api_cloudSetCurrentTime({
  628. currentTime: itemTime * 1000,
  629. songID: state.examSongId,
  630. })
  631. audioData.progress = itemTime
  632. state.midiSectionStart = itemTime
  633. }
  634. }
  635. };
  636. /**
  637. * 切换曲谱播放状态
  638. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  639. */
  640. export const togglePlay = async (playState?: "play" | "paused", sourceType?: string) => {
  641. // 如果mp3资源还在加载中,给出提示
  642. if (!state.isAppPlay && !state.audioDone) {
  643. if (sourceType !== 'courseware') showToast('音频资源加载中,请稍后')
  644. return
  645. }
  646. // midi播放
  647. if (state.isAppPlay) {
  648. if( playState === "paused" ) {
  649. await api_cloudSuspend({
  650. songID: state.examSongId,
  651. })
  652. state.playState = 'paused'
  653. return
  654. }
  655. skipNotePlay(state.activeNoteIndex, false);
  656. await api_cloudChangeSpeed({
  657. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  658. originalSpeed: state.originSpeed,
  659. songID: state.examSongId,
  660. });
  661. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  662. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  663. state.playState = status
  664. } else {
  665. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  666. }
  667. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  668. resetPlaybackToStart();
  669. }
  670. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  671. if (state.playState === "play" && state.needTick) {
  672. const tickend = await handleStartTick();
  673. // console.log("🚀 ~ tickend:", tickend)
  674. // 节拍器返回false, 取消播放
  675. if (!tickend) {
  676. state.playState = "paused";
  677. return false;
  678. }
  679. }
  680. // 如果选段没有结束, 直接开始播放,清空选段状态
  681. if (state.playState == "play") {
  682. if (state.sectionStatus && state.section.length < 2) {
  683. clearSelection();
  684. }
  685. }
  686. audioListStart(state.playState);
  687. return true;
  688. };
  689. /** 结束播放 */
  690. export const handleStopPlay = () => {
  691. state.playState = "paused";
  692. audioListStart(state.playState);
  693. };
  694. /** 重置播放为开始 */
  695. export const resetPlaybackToStart = () => {
  696. // 如果为选段状态
  697. if (state.sectionStatus && state.section.length === 2) {
  698. state.section = formateSelectMearure(state.section);
  699. return;
  700. } else {
  701. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  702. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  703. }
  704. skipNotePlay(0, true);
  705. };
  706. /** 跳转到指定音符 */
  707. export const gotoCustomNote = (index: number) => {
  708. try {
  709. state.osmd.cursor.reset();
  710. } catch (error) {}
  711. for (let i = 0; i < index; i++) {
  712. state.osmd.cursor.next();
  713. }
  714. };
  715. const setCursorPosition = (note: any, cursor: any) => {
  716. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  717. /**
  718. * bug:#9920、#9940
  719. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  720. */
  721. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  722. return
  723. }
  724. nextTick(() => {
  725. let bbox = note.bbox;
  726. if (!bbox) {
  727. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  728. x: 0,
  729. y: 0,
  730. };
  731. const parentLeft = musicContainer.x || 0;
  732. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  733. if (noteEle) {
  734. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  735. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  736. if (noteHeadBbox) {
  737. note.bbox = {
  738. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  739. width: noteHeadBbox.width * 1.5,
  740. };
  741. bbox = note.bbox;
  742. }
  743. }
  744. }
  745. if (!bbox) return;
  746. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  747. const width = (bbox.width - baseW) / 3;
  748. // console.log(555555,bbox.left,width)
  749. cursor.cursorElement.style.left = bbox.left + "px";
  750. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  751. });
  752. }
  753. };
  754. /**
  755. * 跳转到下一个音符
  756. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  757. **/
  758. export const gotoNext = (note: any, skipNote?: boolean) => {
  759. // console.log(33333333333,state.activeNoteIndex,note.i)
  760. const num = note.i;
  761. if (state.activeNoteIndex === note.i) {
  762. try {
  763. setCursorPosition(note, state.osmd.cursor);
  764. } catch (error) {
  765. console.log(error);
  766. }
  767. return;
  768. }
  769. const osmd = state.osmd;
  770. let prev = state.activeNoteIndex;
  771. state.activeNoteIndex = num;
  772. state.activeMeasureIndex = note.MeasureNumberXML;
  773. if (prev && num - prev === 1) {
  774. osmd.cursor.next();
  775. } else if (prev && num - prev > 0) {
  776. while (num - prev > 0) {
  777. prev++;
  778. osmd.cursor.next();
  779. }
  780. } else {
  781. gotoCustomNote(num);
  782. }
  783. try {
  784. setCursorPosition(note, state.osmd.cursor);
  785. } catch (error) {
  786. console.log(error);
  787. }
  788. // 一行谱,需要滚动小节
  789. if (state.isSingleLine) {
  790. moveSvgDom(skipNote);
  791. }
  792. scrollViewNote();
  793. };
  794. /** 获取指定音符 */
  795. export const getNote = (currentTime: number) => {
  796. const times = state.times;
  797. const len = state.times.length;
  798. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  799. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  800. onEnded();
  801. return;
  802. }
  803. let _item = null as any;
  804. for (let i = state.activeNoteIndex; i < len; i++) {
  805. const item = times[i];
  806. const prevItem = times[i - 1];
  807. if (currentTime >= item.time) {
  808. if (!prevItem || item.time != prevItem.time) {
  809. _item = item;
  810. }
  811. } else {
  812. break;
  813. }
  814. }
  815. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  816. return _item;
  817. };
  818. /** 重播 */
  819. export const handleResetPlay = () => {
  820. // 如果是midi需要重置播放进度
  821. if (state.isAppPlay) {
  822. audioData.progress = 0
  823. }
  824. resetPlaybackToStart();
  825. // 如果是暂停, 直接播放
  826. togglePlay("play");
  827. };
  828. /** 设置速度 */
  829. export const handleSetSpeed = (speed: number) => {
  830. setStorageSpeed(state.examSongId, speed);
  831. state.speed = speed;
  832. };
  833. /** 清除选段状态 */
  834. export const clearSelection = () => {
  835. state.sectionStatus = false;
  836. state.section = [];
  837. closeToast();
  838. };
  839. /** 开启选段 */
  840. export const handleChangeSection = () => {
  841. // 如果开启了选段,再次点击取消选段
  842. if (state.sectionStatus) {
  843. togglePlay("paused");
  844. clearSelection();
  845. skipNotePlay(0, true);
  846. state.sectionFirst = null;
  847. return;
  848. }
  849. state.sectionStatus = true;
  850. // 开启
  851. if (state.sectionStatus) {
  852. togglePlay("paused");
  853. }
  854. showToast({
  855. message: "请选择开始小节",
  856. duration: 0,
  857. position: "top",
  858. className: "selectionToast",
  859. });
  860. };
  861. /** 效验并格式化选段小节 */
  862. const formateSelectMearure = (_list: any[]): any[] => {
  863. if (!_list.length) return [];
  864. const list = _list.sort((a, b) => a.time - b.time);
  865. const startXml = list[0]?.measureOpenIndex;
  866. const endXml = list.last()?.measureOpenIndex;
  867. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  868. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  869. // 没有找到选段小节
  870. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  871. clearSelection();
  872. return [];
  873. }
  874. list[0] = selectStartMeasure[0];
  875. list[1] = selectEndMeasure.last();
  876. let startItemINdex = list[0].i;
  877. // 开启预备拍
  878. if (state.isOpenPrepare) {
  879. const startXmlIndex = list[0].MeasureNumberXML;
  880. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  881. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  882. }
  883. skipNotePlay(startItemINdex, startItemINdex === 0);
  884. return list;
  885. };
  886. /** 选择选段 */
  887. export const handleSelection = (item: any) => {
  888. if (!state.sectionStatus || state.section.length > 1) return;
  889. if (state.section.length !== 2 && item) {
  890. state.section.push(item);
  891. if (state.section.length === 2) {
  892. setSection(state.section[0].MeasureNumberXML,state.section[1].MeasureNumberXML)
  893. //state.section = formateSelectMearure(state.section);
  894. closeToast();
  895. }
  896. }
  897. if (state.section.length === 1) {
  898. showToast({
  899. message: "请选择结束小节",
  900. duration: 0,
  901. position: "top",
  902. className: "selectionToast",
  903. });
  904. }
  905. };
  906. /** 阶段练习、阶段评测设置选段小节 */
  907. export const setSection = (start: number, end: number, userSpeed?: number) => {
  908. const startNotes = state.times.filter(
  909. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  910. )
  911. const endNotes = state.times.filter(
  912. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  913. )
  914. state.userChooseEndIndex = end
  915. const lastEndId = endNotes[endNotes.length - 1].noteId
  916. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  917. // 是否符合重播规则
  918. const canRepeatInfo = verifyCanRepeat(start, end)
  919. console.log('能否重播',canRepeatInfo)
  920. const isCanRepeat = canRepeatInfo.canRepeat
  921. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  922. /**
  923. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  924. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  925. * TODO:通过vf-volta判断是否是跳房子
  926. */
  927. let isSkipVolta = false; // 结束小节是否是跳房子小节
  928. if (lastEndNotes.length === 1) {
  929. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  930. }
  931. let currentEndNum: number = end
  932. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  933. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  934. currentEndNum = currentEndNum - 1
  935. const newEndNotes = state.times.filter(
  936. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  937. )
  938. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  939. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  940. }
  941. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  942. const startNote = startNotes[0]
  943. // const endNote = endNotes[endNotes.length - 1]
  944. const endNote = lastEndNotes[endIdx]
  945. if (startNote && endNote) {
  946. state.isSelectMeasureMode = true;
  947. // 设置小节
  948. hanldeDirectSelection([startNote, endNote]);
  949. //设置速度
  950. if (userSpeed) {
  951. handleSetSpeed(userSpeed);
  952. }
  953. }
  954. }
  955. /** 直接设置选段 */
  956. export const hanldeDirectSelection = (list: any[]) => {
  957. if (!Array.isArray(list) || list.length !== 2) return;
  958. state.sectionStatus = true;
  959. setTimeout(() => {
  960. state.section = formateSelectMearure(list);
  961. console.log('选段小节',state.section)
  962. }, 500);
  963. };
  964. let offsetTop = 0;
  965. /**
  966. * 窗口内滚动到音符的区域
  967. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  968. * @returns void
  969. */
  970. export const scrollViewNote = () => {
  971. const cursorElement = document.getElementById("cursorImg-0")!;
  972. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  973. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  974. offsetTop = cursorElement.offsetTop;
  975. if (offsetTop > 50) {
  976. musicAndSelection.scrollTo({
  977. top: (offsetTop - 50) * state.musicZoom,
  978. behavior: "smooth",
  979. });
  980. } else {
  981. musicAndSelection.scrollTo({
  982. top: 0,
  983. behavior: "smooth",
  984. });
  985. }
  986. };
  987. /** 检测是否是节奏练习 */
  988. export const isRhythmicExercises = () => {
  989. return state.examSongName.indexOf("节奏练习") > -1;
  990. };
  991. /** 重置状态 */
  992. export const handleRessetState = () => {
  993. // 切换模式,清除选段
  994. clearSelection();
  995. skipNotePlay(0, true);
  996. // midi 重置播放进度
  997. if (state.isAppPlay) {
  998. audioData.progress = 0;
  999. }
  1000. if (state.modeType === "evaluating") {
  1001. handleStartEvaluat();
  1002. } else if (state.modeType === "practise") {
  1003. togglePlay("paused");
  1004. } else if (state.modeType === "follow") {
  1005. toggleFollow(false);
  1006. }
  1007. };
  1008. export default state;
  1009. /** 初始化评测音频 */
  1010. export const evaluatCreateMusicPlayer = () => {
  1011. return api_createMusicPlayer({
  1012. musicSrc: state.accompany || state.music, // 曲谱音频url
  1013. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1014. });
  1015. };
  1016. /** 获取内容平台的接口详情并初始化state信息 */
  1017. export const getMusicDetail = async (id: string) => {
  1018. const res = await getMusicSheetDetail(id);
  1019. if (res?.code === 200) {
  1020. getMusicInfo(res)
  1021. }
  1022. };
  1023. const getMusicInfo = (res: any) => {
  1024. const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
  1025. // 原音声轨
  1026. const musicData = res.data.musicSheetSoundList?.[index] || {};
  1027. // 伴奏声轨
  1028. const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
  1029. const musicInfo = {
  1030. ...res.data,
  1031. music: musicData.audioFileUrl || '',
  1032. accompany: accompanyData.audioFileUrl || '',
  1033. musicSheetId: musicData.musicSheetId || res.data.bizId,
  1034. track: musicData.track || '',
  1035. };
  1036. console.log("🚀 ~ musicInfo:", musicInfo);
  1037. setState(musicInfo, index);
  1038. };
  1039. const setState = (data: any, index: number) => {
  1040. state.appName = "COLEXIU";
  1041. state.detailId = data.bizId;
  1042. state.xmlUrl = data.xmlFileUrl;
  1043. state.partIndex = index;
  1044. state.trackId = data.track;
  1045. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1046. // 声部code
  1047. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1048. // 乐器code
  1049. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1050. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1051. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1052. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1053. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1054. state.categoriesId = data.musicCategoryId;
  1055. state.categoriesName = data.musicTagNames;
  1056. // state.enableEvaluation = data.isEvaluated ? true : false;
  1057. state.examSongId = data.bizId + "";
  1058. state.cbsExamSongId = data.id + "";
  1059. state.examSongName = data.name;
  1060. state.coverImg = data.musicCover ?? "";
  1061. // 单声部多声轨合并展示
  1062. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1063. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1064. // 解析扩展字段
  1065. if (data.extConfigJson) {
  1066. try {
  1067. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1068. } catch (error) {
  1069. console.error("解析扩展字段错误:", error);
  1070. }
  1071. }
  1072. state.gradualTimes = state.extConfigJson.gradualTimes;
  1073. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1074. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1075. // 曲子包含节拍器,就不开启节拍器
  1076. state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
  1077. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1078. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1079. state.isShowFingering = data.isShowFingering ? true : false;
  1080. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1081. state.isAppPlay = data.playMode === 'MIDI';
  1082. state.music = data.music;
  1083. state.accompany = data.accompany;
  1084. state.midiUrl = data.midiFileUrl;
  1085. state.parentCategoriesId = data.musicTag;
  1086. state.musicSheetCategoriesId = data.musicCategoryId;
  1087. state.bizMusicCategoryId = data.bizMusicCategoryId
  1088. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1089. state.originSpeed = state.speed = parseFloat(data.playSpeed) || 0;
  1090. // state.originSpeed = state.speed = data.playSpeed;
  1091. // state.playIngSpeed = data.playSpeed;
  1092. const track = data.code || data.track;
  1093. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1094. // 能否评测,根据当前声轨有无伴奏判断
  1095. if (state.isAppPlay) {
  1096. state.enableEvaluation = state.midiUrl ? true : false
  1097. } else {
  1098. state.enableEvaluation = state.accompany ? true : false
  1099. }
  1100. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1101. // multiTracksSelection 返回为空,默认代表全部分轨
  1102. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1103. // 开启预备小节
  1104. state.isOpenPrepare = true;
  1105. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1106. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1107. // 是否打击乐
  1108. /**
  1109. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1110. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1111. * 打击乐&节奏练习,没有跟练模式
  1112. */
  1113. // state.isPercussion = isRhythmicExercises();
  1114. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1115. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1116. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1117. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1118. // 设置指法
  1119. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1120. /**
  1121. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1122. * 获取指法code
  1123. */
  1124. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1125. state.fingeringInfo = subjectFingering(code);
  1126. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1127. state.musicalCodeId = state.fingeringInfo?.id || 0
  1128. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1129. ;(window as any).DYSubjectId = state.musicalCodeId
  1130. // 开启自定义每行显示的小节数
  1131. ;(window as any).customSectionAmount = true
  1132. // 标识是课堂乐器,用于移调时进行区分处理
  1133. ;(window as any).DYProjectName = 'musicScore';
  1134. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1135. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1136. state.setting.displayFingering = false
  1137. }
  1138. // 检测是否原音和伴奏都有
  1139. if (!state.music || !state.accompany) {
  1140. state.playSource = state.music ? "music" : "background";
  1141. }
  1142. // 如果是PC端,放大曲谱
  1143. state.platform = query.platform?.toLocaleUpperCase() || "";
  1144. if (state.platform === IPlatform.PC) {
  1145. state.zoom = query.zoom || 1.5;
  1146. state.enableEvaluation = false;
  1147. }
  1148. /**
  1149. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1150. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1151. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1152. *
  1153. */
  1154. let pitchTrack = null
  1155. if (state.isConcert) {
  1156. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1157. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1158. } else {
  1159. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1160. }
  1161. let musicalRenderType = ''
  1162. if (pitchTrack?.defaultScore) {
  1163. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1164. }
  1165. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1166. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1167. console.log("state对象", state);
  1168. // 评测基准频率
  1169. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1170. state.baseFrequency = Number(state.baseFrequency)
  1171. // 用户上次的频率和基准频率误差超过10,则重置
  1172. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1173. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1174. } else {
  1175. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1176. }
  1177. };
  1178. // 多分轨合并显示标示
  1179. const setCustom = (trackNum?: number) => {
  1180. if (trackNum || state.extConfigJson.multitrack) {
  1181. state.multitrack = trackNum || 0
  1182. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1183. }
  1184. };
  1185. /** 跟练模式播放节拍器(叮咚) */
  1186. export const followBeatPaly = () => {
  1187. let metroTimer: any = null;
  1188. if (!followData.start) {
  1189. clearTimeout(metroTimer)
  1190. metroTimer = null
  1191. return;
  1192. }
  1193. const time = state.measureTime*1000 / metronomeData.totalNumerator
  1194. requestAnimationFrame(() => {
  1195. const endTime = Date.now();
  1196. if (endTime - state.beatStartTime < time) {
  1197. followBeatPaly();
  1198. } else {
  1199. // metroTimer = setTimeout(() => {
  1200. // metronomeData.metro?.simulatePlayAudio()
  1201. // startTime = Date.now();
  1202. // followBeatPaly();
  1203. // }, time);
  1204. metronomeData.metro?.simulatePlayAudio()
  1205. state.beatStartTime = Date.now();
  1206. followBeatPaly();
  1207. }
  1208. });
  1209. };
  1210. // 音符添加bbox
  1211. export const addNoteBBox = (list: any[]) => {
  1212. let voicesBBox: any = null;
  1213. for (let i = 0; i < list.length; i++) {
  1214. const note = list[i];
  1215. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1216. /**
  1217. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1218. */
  1219. let bbox: any = null;
  1220. if (svgElement?.attrs.id) {
  1221. // @ts-ignore
  1222. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1223. bbox = {
  1224. x: bbox?.x * state.zoom,
  1225. y: bbox?.y * state.zoom,
  1226. width: bbox?.width * state.zoom,
  1227. height: bbox?.height * state.zoom,
  1228. }
  1229. } else {
  1230. // @ts-ignore
  1231. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1232. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1233. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1234. currentVoicesBBox = voicesBBox;
  1235. }
  1236. let nextIndex = i + 1;
  1237. while (!list[nextIndex]?.id && nextIndex < list.length) {
  1238. nextIndex += 1;
  1239. }
  1240. // 休止小节的开头和下一个音符之间的间距
  1241. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1242. if (list[nextIndex]?.id) {
  1243. // @ts-ignore
  1244. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1245. }
  1246. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1247. bbox = currentVoicesBBox ? {
  1248. bottom: currentVoicesBBox.bottom,
  1249. height: 30,
  1250. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1251. right: currentVoicesBBox.y,
  1252. top: currentVoicesBBox.top,
  1253. width: 1,
  1254. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1255. y: currentVoicesBBox.y,
  1256. svgBodyLeft: svgBodyBBox?.x,
  1257. } : null;
  1258. voicesBBox = currentVoicesBBox;
  1259. }
  1260. note.bbox = bbox;
  1261. }
  1262. }
  1263. // 一行谱模式,创建固定的光标
  1264. export const createFixedCursor = () => {
  1265. if (!state.isSingleLine) return;
  1266. const svg: any = document.getElementById("osmdSvgPage1");
  1267. state.osmdSvgDom = svg;
  1268. const scrollDom = document.getElementById("musicAndSelection");
  1269. const cursorDom = document.getElementById("cursorImg-0");
  1270. state.fistNoteLeft = cursorDom?.getBoundingClientRect()?.left || 0;
  1271. state.osdmScrollDom = scrollDom;
  1272. state.cursorDom = cursorDom;
  1273. let copyCursor: any = cursorDom?.cloneNode(true);
  1274. if (copyCursor) {
  1275. copyCursor.setAttribute('id','cursor-copy');
  1276. copyCursor.style.position = 'sticky';
  1277. copyCursor.style.zIndex = '2';
  1278. // if (!state.times[0]?.id) {
  1279. // copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 3 + 'px';
  1280. // }
  1281. copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 2 - 1 + 'px';
  1282. copyCursor.style.height = parseFloat(copyCursor.style.height) * 3 + 'px';
  1283. copyCursor.style.opacity = state.moveType === 'uniform' ? 0 : 1;
  1284. // copyCursor.style.background = 'red';
  1285. copyCursor && scrollDom?.appendChild(copyCursor);
  1286. // 创建左侧背景dom
  1287. // @ts-ignore
  1288. const firstMeasureBBox: any = document.querySelector('.vf-measure')?.getBBox();
  1289. const leftDom = document.createElement("div");
  1290. leftDom.style.width = state.times[0]?.bbox?.x - firstMeasureBBox?.x * state.zoom + 'px';
  1291. leftDom.style.height = firstMeasureBBox?.height * state.zoom + 'px';
  1292. leftDom.style.left = firstMeasureBBox?.x * state.zoom + 'px';
  1293. leftDom.style.transform = 'translateY(20px)';
  1294. leftDom.classList.add('leftNoteBg');
  1295. // scrollDom?.appendChild(leftDom);
  1296. }
  1297. }
  1298. /** 计算首尾音符的间距 */
  1299. export const calculateDistance = () => {
  1300. const firstNoteBBox = state.times[0]?.bbox;
  1301. const lastNoteBBox = state.times.last()?.bbox;
  1302. if (firstNoteBBox && lastNoteBBox) {
  1303. const noteDistance = lastNoteBBox.x - firstNoteBBox.x + lastNoteBBox.width / 2 - firstNoteBBox.width / 2 - 1;
  1304. console.log('首尾间距', noteDistance)
  1305. state.noteDistance = noteDistance || 0;
  1306. }
  1307. }
  1308. /** 跳动svgdom */
  1309. export const moveSvgDom = (skipNote?: boolean) => {
  1310. // const cursorLeft = state.cursorDom?.getBoundingClientRect()?.left || 0;
  1311. // const leftValue = parseFloat(state.cursorDom.style.left) - 47 - 20;
  1312. // console.log(cursorLeft,leftValue,'光标位置')
  1313. // state.osmdSvgDom.style.transform = `translateX(${-leftValue}px)`;
  1314. // state.osdmScrollDom.scrollLeft = leftValue
  1315. // console.log('当前音符',state.activeNoteIndex)
  1316. state.times.forEach((item: any, idx: number) => {
  1317. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1318. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1319. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1320. svgEl?.classList.add('noteActive')
  1321. stemEl?.classList.add('noteActive')
  1322. } else {
  1323. svgEl?.classList.remove('noteActive')
  1324. stemEl?.classList.remove('noteActive')
  1325. }
  1326. })
  1327. // document.getElementById('cursor-copy')?.classList.add('cursorAnimate');
  1328. /**
  1329. * 计算需要移动的距离
  1330. * 当前选中的音符和第一个音符之间的间距
  1331. */
  1332. if (skipNote) {
  1333. const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 2 - state.times[0].bbox?.width / 2;
  1334. state.osdmScrollDom.scrollTo({
  1335. left: distance,
  1336. behavior: "smooth",
  1337. });
  1338. }
  1339. }
  1340. /** 平滑移动svgdom */
  1341. export const smoothMoveSvgDom = () => {
  1342. const currentTime = getAudioCurrentTime();
  1343. const matchNoteIdx = state.times.findIndex((item: any) => Math.abs(item.time - currentTime) * 1000 < 100 )
  1344. // if (matchNoteIdx >= 0) {
  1345. // console.log('匹配',matchNoteIdx,currentTime)
  1346. // }
  1347. if (currentTime <= state.fixtime) return;
  1348. if (currentTime > state.times.last()?.time) return;
  1349. // console.log('跳转音符',currentTime)
  1350. const currentBBox = state.times[state.activeNoteIndex]?.bbox;
  1351. let nextIndex = state.activeNoteIndex + 1;
  1352. let nextBBox = state.times[nextIndex]?.bbox;
  1353. while (!nextBBox && nextIndex < state.times.length) {
  1354. nextIndex += 1;
  1355. nextBBox = state.times[nextIndex]?.bbox;
  1356. }
  1357. // 下一个音符和当前播放音符之间的间距
  1358. let noteDistance = nextBBox?.x - state.times[state.activeNoteIndex].bbox?.x + nextBBox?.width / 4 - state.times[state.activeNoteIndex].bbox?.width / 4 || 0
  1359. if (noteDistance) {
  1360. // 当前的音符和下一个音符之间的时值
  1361. const noteDuration = state.times[nextIndex].time - state.times[state.activeNoteIndex]?.time;
  1362. // 当前时值在该区间的占比
  1363. const playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration;
  1364. // 如果当前播放的音符是休止小节的,实际没有音符
  1365. // if (!state.times[state.activeNoteIndex]?.id && state.times[state.activeNoteIndex]?.multipleRestMeasures && state.times[state.activeNoteIndex+1].id) {
  1366. // noteDistance = noteDistance - state.times[state.activeNoteIndex]?.bbox?.svgBodyLeft;
  1367. // }
  1368. const distance = noteDistance * playProgress;
  1369. // 上一个音符和第一个音符的间距
  1370. let preDistance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 4;
  1371. // console.log(state.activeNoteIndex,'滑动', distance, preDistance, state.osdmScrollDom.scrollLeft, noteDistance, nextIndex, currentTime, noteDuration )
  1372. // console.log('当前音符',state.activeNoteIndex,'距离',noteDistance,'比例',playProgress,'上一个距离',preDistance,'时值',currentTime, noteDuration)
  1373. //console.log('滑动','音符:',state.activeNoteIndex,'小节:', state.activeMeasureIndex)
  1374. state.osdmScrollDom.scrollLeft = distance + preDistance;
  1375. } else {
  1376. const playProgress = (currentTime - state.times[0]?.time) / state.times.last()?.time
  1377. const distance = state.noteDistance * playProgress;
  1378. state.osdmScrollDom.scrollLeft = distance;
  1379. }
  1380. }
  1381. // 匀速平移
  1382. export const uniformMoveSvgDom = () => {
  1383. const currentTime = getAudioCurrentTime();
  1384. if (currentTime <= state.fixtime) return;
  1385. if (currentTime > state.times.last()?.time) return;
  1386. const playProgress = (currentTime - state.fixtime) / state.times.last()?.time;
  1387. const distance = playProgress * state.noteDistance || 0;
  1388. state.osdmScrollDom.scrollLeft = distance;
  1389. }