state.ts 47 KB

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