state.ts 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. import { closeToast, showToast } from "vant";
  2. import { nextTick, reactive, watch } 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, closeTick } 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, skipNotePractice } from "/src/view/follow-practice/index"
  17. import { changeSongSourceByBate } from "/src/view/audio-list"
  18. import { moveSmoothAnimation, smoothAnimationState, moveSmoothAnimationByPlayTime, moveTranslateXNum, destroySmoothAnimation } from "/src/page-instrument/view-detail/smoothAnimation"
  19. import { storeData } from "/src/store";
  20. import { downloadXmlStr } from "./view/music-score"
  21. import { musicScoreRef } from "/src/page-instrument/view-detail/index"
  22. const query: any = getQuery();
  23. /** 入门 | 进阶 | 大师 */
  24. export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
  25. /** 渲染类型: 五线谱,简谱 */
  26. export enum EnumMusicRenderType {
  27. /** 五线谱 */
  28. staff = "staff",
  29. /** 简谱 */
  30. firstTone = "firstTone",
  31. /** 固定音高 */
  32. fixedTone = "fixedTone",
  33. }
  34. export const musicscoresettingKey = "musicscoresetting";
  35. /** 有声音的是那个音源 */
  36. export type IPlayState = "music" | "background" | "mingSong";
  37. /** 播放状态 */
  38. export type IAudioState = "play" | "paused";
  39. /** 来源 */
  40. export enum IPlatform {
  41. APP = "APP",
  42. PC = "PC",
  43. }
  44. export type ISonges = {
  45. background?: string
  46. music?: string
  47. }
  48. /**
  49. * 特殊教材分类id
  50. */
  51. 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
  52. // 乐器code码
  53. export const musicalInstrumentCodeInfo = [
  54. {
  55. name: '长笛',
  56. code: 'Flute',
  57. id: 1
  58. },
  59. {
  60. name: '短笛',
  61. code: 'Piccolo',
  62. id: 2
  63. },
  64. {
  65. name: '单簧管',
  66. code: 'Clarinet',
  67. id: 3
  68. },
  69. {
  70. name: '低音单簧管',
  71. code: 'Bass Clarinet',
  72. id: 4
  73. },
  74. {
  75. name: '中音萨克斯',
  76. code: 'Alto Saxophone',
  77. id: 5
  78. },
  79. {
  80. name: '次中音萨克斯',
  81. code: 'Tenor Saxophone',
  82. id: 6
  83. },
  84. {
  85. name: '高音萨克斯',
  86. code: 'Soprano Saxophone',
  87. id: 7
  88. },
  89. {
  90. name: '上低音萨克斯',
  91. code: 'Baritone Saxophone',
  92. id: 8
  93. },
  94. {
  95. name: '双簧管',
  96. code: 'Oboe',
  97. id: 9
  98. },
  99. {
  100. name: '大管',
  101. code: 'Bassoon',
  102. id: 10
  103. },
  104. {
  105. name: '小号',
  106. code: 'Trumpet',
  107. id: 11
  108. },
  109. {
  110. name: '圆号',
  111. code: 'Horn',
  112. id: 12
  113. },
  114. {
  115. name: '长号',
  116. code: 'Trombone',
  117. id: 13
  118. },
  119. {
  120. name: '上低音号',
  121. code: 'Baritone',
  122. id: 14
  123. },
  124. {
  125. name: '次中音号',
  126. code: 'Euphonium',
  127. id: 15
  128. },
  129. {
  130. name: '大号',
  131. code: 'Tuba',
  132. id: 16
  133. },
  134. {
  135. name: '钢琴',
  136. code: 'Piano',
  137. id: 17
  138. },
  139. {
  140. name: '电钢琴',
  141. code: 'Electronical Piano',
  142. id: 18
  143. },
  144. {
  145. name: '钢片琴',
  146. code: 'Glockenspiel',
  147. id: 19
  148. },
  149. {
  150. name: '小提琴',
  151. code: 'Violin',
  152. id: 20
  153. },
  154. {
  155. name: '中提琴',
  156. code: 'Viola',
  157. id: 21
  158. },
  159. {
  160. name: '大提琴',
  161. code: 'Violoncello',
  162. id: 22
  163. },
  164. {
  165. name: '低音提琴',
  166. code: 'Contrabass',
  167. id: 23
  168. },
  169. {
  170. name: '架子鼓',
  171. code: 'Drum Set',
  172. id: 24
  173. },
  174. {
  175. name: '小鼓',
  176. code: 'Snare Drum',
  177. id: 25
  178. },
  179. {
  180. name: '马林巴',
  181. code: 'Marimba',
  182. id: 26
  183. },
  184. {
  185. name: '颤音琴',
  186. code: 'Vibraphone',
  187. id: 27
  188. },
  189. {
  190. name: '钟琴',
  191. code: 'Chimes',
  192. id: 28
  193. },
  194. {
  195. name: '木琴',
  196. code: 'Xylophone',
  197. id: 29
  198. },
  199. {
  200. name: '管钟',
  201. code: 'Tubular Bells',
  202. id: 30
  203. },
  204. {
  205. name: '定音鼓',
  206. code: 'Timpani',
  207. id: 31
  208. },
  209. {
  210. name: '键盘',
  211. code: 'Mallets',
  212. id: 32
  213. },
  214. {
  215. name: '排箫',
  216. code: 'Panpipes',
  217. id: 33
  218. },
  219. {
  220. name: '陶笛',
  221. code: 'Ocarina',
  222. id: 34
  223. },
  224. {
  225. name: '葫芦丝',
  226. code: 'Woodwind',
  227. id: 35
  228. },
  229. {
  230. name: '口风琴',
  231. code: 'Nai',
  232. id: 36
  233. },
  234. {
  235. name: '德式竖笛',
  236. code: 'Tenor Recorder',
  237. id: 37
  238. },
  239. {
  240. name: '英式竖笛',
  241. code: 'Baroque Recorder',
  242. id: 38
  243. },
  244. {
  245. name: '高音陶笛',
  246. code: 'Whistling',
  247. id: 39
  248. },
  249. ]
  250. const state = reactive({
  251. /** 来源 : PC , app */
  252. platform: "" as IPlatform,
  253. appName: "" as "GYM" | "COLEXIU",
  254. musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
  255. /**曲谱是否渲染完成 */
  256. musicRendered: false,
  257. /** 当前曲谱数据ID, 和曲谱ID不一致 */
  258. detailId: "",
  259. /** 曲谱资源URL */
  260. xmlUrl: "",
  261. /** 声部ID */
  262. subjectId: 0 as number,
  263. trackId: 0 as string | number,
  264. isVip: false, // 是否会员
  265. /** 分类ID */
  266. categoriesId: 0,
  267. /** 分类名称 */
  268. categoriesName: "",
  269. /** 是否支持评测 */
  270. enableEvaluation: true,
  271. /** 是否支持转谱 */
  272. enableNotation: false,
  273. /** 曲谱ID */
  274. examSongId: "",
  275. /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
  276. cbsExamSongId: "",
  277. /** 曲谱名称 */
  278. examSongName: "",
  279. /** 曲谱封面 */
  280. coverImg: "",
  281. /** 扩展字段 */
  282. extConfigJson: {} as any,
  283. /** 扩展样式字段 */
  284. extStyleConfigJson: {} as any,
  285. /** 是否开启节拍器(mp3节拍器) */
  286. isOpenMetronome: false,
  287. /** 演唱模式是否开启节拍器(mp3节拍器) */
  288. isSingOpenMetronome: false,
  289. /** 是否显示指法 */
  290. isShowFingering: false,
  291. /** 原音 */
  292. music: "",
  293. /** 伴奏 */
  294. accompany: "",
  295. /** 范唱 */
  296. fanSong: "",
  297. /** 伴唱 */
  298. banSong: "",
  299. /** 唱名 */
  300. mingSong: "",
  301. /** 节拍器音乐资源 */
  302. beatSong: {
  303. music: "",
  304. accompany: "",
  305. fanSong: "",
  306. banSong: "",
  307. mingSong: ""
  308. },
  309. /** midiURL */
  310. midiUrl: "",
  311. /** 父分ID */
  312. parentCategoriesId: 0,
  313. /** 分类ID */
  314. musicSheetCategoriesId: 0,
  315. /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
  316. bizMusicCategoryId: 0,
  317. /** 资源类型: mp3 | midi */
  318. playMode: "MP3" as "MP3" | "MIDI",
  319. /** 设置的速度 */
  320. speed: 0,
  321. /** 曲谱音频正常的速度 */
  322. originSpeed: 0,
  323. /** 播放过程中显示的速度 */
  324. playIngSpeed: 0,
  325. /** 分轨名称 */
  326. track: "",
  327. /** 当前显示声部索引 */
  328. partIndex: 0,
  329. /** 演奏是否需要节拍器 */
  330. needTick: false,
  331. /** 演唱模式是否需要节拍器 */
  332. needSingTick: false,
  333. /** 曲谱实例 */
  334. osmd: null as unknown as OpenSheetMusicDisplay,
  335. /**是否是特殊乐谱类型, 主要针对管乐迷 */
  336. isSpecialBookCategory: false,
  337. /** 播放状态 */
  338. playState: "paused" as IAudioState,
  339. /** 播放结束状态 */
  340. playEnd: false,
  341. /** 播放类型 演奏 演唱 */
  342. playType: "play" as "play" | "sing",
  343. /** 播放那个: 原音,伴奏 */
  344. playSource: "music" as IPlayState,
  345. /** 播放进度 */
  346. playProgress: 0,
  347. /** 激活的note index */
  348. activeNoteIndex: 0,
  349. /** 激活的小节 */
  350. activeMeasureIndex: 0,
  351. /** 选段状态 */
  352. sectionStatus: false,
  353. /** 选段数据 */
  354. section: [] as any[],
  355. /** 选段背景 */
  356. sectionBoundingBoxs: [] as any[],
  357. /** 开启选段预备 */
  358. isOpenPrepare: false,
  359. /** 选段预备 */
  360. sectionFirst: null as any,
  361. /** 音符数据 */
  362. times: [] as any[],
  363. /** 播放模式 */
  364. modeType: "practise" as "practise" | "follow" | "evaluating",
  365. /** 设置 */
  366. setting: {
  367. /** 效音提醒 */
  368. soundEffect: true,
  369. /** 护眼模式 */
  370. eyeProtection: false,
  371. /** 摄像头 */
  372. camera: false,
  373. /** 摄像头透明度 */
  374. cameraOpacity: 70,
  375. /** 循环播放 */
  376. repeatAutoPlay: true,
  377. /** 显示指法 */
  378. displayFingering: true,
  379. /** 显示光标 */
  380. displayCursor: true,
  381. /** 频率 */
  382. frequency: 0,
  383. /** 评测难度 */
  384. evaluationDifficulty: "BEGINNER" as IDifficulty,
  385. /** 保存到相册 */
  386. saveToAlbum: true,
  387. /** 开启伴奏 */
  388. enableAccompaniment: true,
  389. /** 反应时间 */
  390. reactionTimeMs: 0,
  391. /** 节拍器音量 */
  392. beatVolume: 50
  393. },
  394. /** 后台设置的基准评测频率 */
  395. baseFrequency: 440,
  396. /** mp3节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
  397. fixtime: 0,
  398. /** evxml等待播放的时间 */
  399. evXmlBeginTime: 0,
  400. /** 第二遍循环evxml等待播放的时间 */
  401. secondEvXmlBeginTime: 0,
  402. /** evxml等待播放的时间集合,多遍反复播放,会有多个timegap(前奏)时间 */
  403. evXmlBeginArr: [] as any,
  404. /** 指法信息 */
  405. fingeringInfo: {} as IFingering,
  406. /** 滚动容器的ID */
  407. scrollContainer: "musicAndSelection",
  408. /** 是否是打击乐 */
  409. isPercussion: false,
  410. /** 评测标准 */
  411. evaluationStandard: '',
  412. /** 是否重复节拍器的时间 */
  413. repeatedBeats: 0,
  414. /**当前曲谱中所有声部名字 */
  415. partListNames: [] as any,
  416. /** 渐变速度信息 */
  417. gradual: [] as GradualNote[],
  418. /** 渐变速度版本 */
  419. gradualVersion: GradualVersion.BASE as GradualVersion,
  420. /** 渐变时间信息 */
  421. gradualTimes: null as GradualTimes,
  422. /** 单声部多声轨 */
  423. multitrack: 0,
  424. /** 缩放 */
  425. zoom: 0.8,
  426. /** 渲染曲谱比例 */
  427. musicZoom: 1,
  428. /** 练习,评测是否是选段模式 */
  429. isSelectMeasureMode: false,
  430. /** 是否是评分显示 */
  431. isReport: false,
  432. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  433. isHideEvaluatReportSaveBtn: false,
  434. /** 是否是合奏 */
  435. isConcert: false,
  436. /** 用户选择的结束小节数 */
  437. userChooseEndIndex: 0,
  438. /** 重播小节集合信息 */
  439. repeatInfo: [] as any,
  440. /** 多分轨的曲子,可支持筛选的分轨 */
  441. canSelectTracks: [] as any,
  442. /** 声部codeId */
  443. subjectCodeId: 0 as number,
  444. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  445. musicalCodeId: 0 as number,
  446. /** 乐器code,用于评测传参 */
  447. musicalCode: '' as any,
  448. /** 合奏曲目是否合并展示 */
  449. isCombineRender: false,
  450. /** 小节的持续时长,以后台设置的播放速度计算 */
  451. measureTime: 0,
  452. /** 跟练模式,节拍器播放的时间 */
  453. beatStartTime: 0,
  454. /** 是否为详情预览模式 */
  455. isPreView: false,
  456. /** 是否为评测报告模式 */
  457. isEvaluatReport: false,
  458. /** midi播放器是否初始化中 */
  459. midiPlayIniting: false,
  460. /** 曲目信息 */
  461. songs: {} as ISonges,
  462. isAppPlay: false, // 是否midi音频,midi是app播放
  463. /** 音频播放器实例 */
  464. audiosInstance: null as any,
  465. /** midi音频的时长 */
  466. durationNum: 0,
  467. midiSectionStart: 0,
  468. /** 音频文件是否加载完成 */
  469. audioDone: false,
  470. /** 是否为单行谱渲染模式 */
  471. isSingleLine: false,
  472. /** 是否是evxml */
  473. isEvxml: false,
  474. noTimes: [] as any,
  475. /** 老师端:功能按钮布局方向 */
  476. playBtnDirection: "left" as "left" | "right",
  477. /** 云练习按钮方向,如果有指法并且是竖向的指法,为了防止播放按钮把指法挡住,此时云练习播放按钮方向应该取反 */
  478. musicScoreBtnDirection: "right" as "left" | "right",
  479. /** 是否在老师端上课页面 */
  480. isAttendClass: false,
  481. /** 引导页信息 */
  482. guideInfo: null as any,
  483. noteCoords: [] as any,
  484. specialPosInit: false,
  485. /** 资源类型 */
  486. paymentType: null,
  487. /** 播放模式,默认练习模式 */
  488. defaultModeType: 1,
  489. /** 音符最多歌词次数 */
  490. maxLyricNum: 0,
  491. /** 小节dom集合 */
  492. vfmeasures: [] as SVGAElement[],
  493. /** 作曲家 */
  494. musicComposer: '',
  495. /** 作词家 */
  496. musicLyricist: '',
  497. /** 加载中的文案 */
  498. loadingText: '音频资源加载中,请稍后…',
  499. });
  500. const browserInfo = browser();
  501. let offset_duration = 0;
  502. /** 自定义数据 */
  503. export const customData = reactive({
  504. /** 自定义音符时值 */
  505. customNoteRealValue: [] as any,
  506. /** 自定义音符按读取到的时值 */
  507. customNoteCurrentTime: false,
  508. });
  509. /** 在渲染前后计算光标应该走到的音符 */
  510. const setStep = () => {
  511. // console.log('播放状态',state.playState)
  512. if (state.playState !== "play") {
  513. console.log("暂停播放");
  514. return;
  515. }
  516. let startTime = Date.now();
  517. requestAnimationFrame(() => {
  518. const endTime = Date.now();
  519. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  520. if (endTime - startTime < 16.7) {
  521. handlePlaying();
  522. setStep();
  523. } else {
  524. setTimeout(() => {
  525. handlePlaying();
  526. setStep();
  527. }, 16.7);
  528. }
  529. });
  530. };
  531. /** 开始播放 */
  532. export const onPlay = () => {
  533. console.log("开始播放", '音频总时长:', getAudioDuration());
  534. state.playEnd = false;
  535. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  536. offset_duration = 0.2;
  537. setStep();
  538. };
  539. /** 播放模式结束自动重播 */
  540. const autoResetPlay = () => {
  541. if (state.modeType !== "practise") return;
  542. skipNotePlay(0, true);
  543. // 没有开启自动重播, 不是练习模式
  544. if (!state.setting.repeatAutoPlay) return;
  545. scrollViewNote();
  546. setTimeout(() => {
  547. togglePlay("play");
  548. }, 1000);
  549. };
  550. /** 播放完成事件 */
  551. export const onEnded = () => {
  552. console.log("音频播放结束");
  553. // if (state.isAppPlay) {
  554. // // 销毁播放器
  555. // api_cloudDestroy();
  556. // }
  557. if (state.playEnd) {
  558. console.log('音频播放结束,无需再次执行')
  559. return
  560. }
  561. // 修改状态为结束
  562. state.playEnd = true;
  563. state.playState = "paused";
  564. // 结束播放
  565. audioListStart(state.playState);
  566. // 调用结束评测
  567. handleEndEvaluat(true);
  568. // 调用自动重复播放
  569. autoResetPlay();
  570. };
  571. /**
  572. * 播放一直触发的事件
  573. */
  574. const handlePlaying = () => {
  575. const currentTime = getAudioCurrentTime();
  576. const duration = getAudioDuration();
  577. state.playProgress = (currentTime / duration) * 100;
  578. let item = getNote(currentTime);
  579. // console.log(11111,currentTime,duration,state.playSource, item)
  580. // console.log(item?.i,item?.noteId,item?.measureSpeed,'播放')
  581. // 练习模式下,实时刷新小节速度
  582. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  583. const ratio = state.speed / state.originSpeed
  584. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  585. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  586. state.playIngSpeed = state.speed
  587. }
  588. state.playIngSpeed = state.playIngSpeed || state.speed;
  589. if (item) {
  590. // 选段状态下
  591. if (state.sectionStatus && state.section.length === 2) {
  592. // 如果开启了预备拍
  593. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  594. const selectEndItem = state.section[1];
  595. /**
  596. * #9374,反复小节的曲目播放错误, bug修复
  597. * 曲目:噢!苏珊娜-排箫-人音
  598. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  599. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  600. */
  601. if (state.repeatInfo.length) {
  602. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  603. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  604. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  605. const preItem = state.times[item.i - 1]
  606. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  607. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  608. if (skipItem) {
  609. // 跳转到指定的音频位置
  610. setAudioCurrentTime(skipItem.time, skipItem.i);
  611. gotoNext(skipItem);
  612. return
  613. }
  614. }
  615. }
  616. }
  617. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  618. // if (currentTime - selectEndItem.endtime > offset_duration) {
  619. //console.log(currentTime,selectEndItem.endtime)
  620. if (currentTime - selectEndItem.endtime >= 0) {
  621. console.log("选段播放结束", state.setting.repeatAutoPlay);
  622. // 如果为选段评测模式
  623. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  624. onEnded();
  625. return;
  626. }
  627. // #8698 bug修复
  628. if (state.modeType === "practise" && state.sectionStatus) {
  629. onEnded();
  630. resetPlaybackToStart();
  631. return;
  632. }
  633. item = selectStartItem;
  634. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  635. }
  636. }
  637. gotoNext(item);
  638. }
  639. // 评测不播放叮咚节拍器
  640. // if (state.modeType !== "evaluating") {
  641. // metronomeData.metro?.sound(currentTime);
  642. // }
  643. metronomeData.metro?.sound(currentTime);
  644. // 一行谱,需要滚动小节
  645. if (state.isSingleLine) {
  646. moveSmoothAnimationByPlayTime()
  647. }
  648. };
  649. /** 跳转到指定音符开始播放 */
  650. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  651. const item = state.times[itemIndex];
  652. let itemTime = item.time;
  653. if (isStart) {
  654. itemTime = 0;
  655. }
  656. if (item) {
  657. setAudioCurrentTime(itemTime, itemIndex);
  658. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  659. gotoNext(item, true);
  660. metronomeData.metro?.sound(itemTime);
  661. if (state.isAppPlay) {
  662. await api_cloudSetCurrentTime({
  663. currentTime: itemTime * 1000,
  664. songID: state.examSongId,
  665. })
  666. audioData.progress = itemTime
  667. state.midiSectionStart = itemTime
  668. }
  669. // 如果是跟练模式
  670. if (followData.start) {
  671. skipNotePractice()
  672. }
  673. }
  674. };
  675. /**
  676. * 切换曲谱播放状态
  677. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  678. */
  679. export const togglePlay = async (playState?: "play" | "paused", sourceType?: string) => {
  680. // 如果mp3资源还在加载中,给出提示
  681. if (!state.isAppPlay && !state.audioDone) {
  682. if (sourceType !== 'courseware') showToast('音频资源加载中,请稍后')
  683. return
  684. }
  685. // 播放之前 当为评测模式和不为MIDI时候按 是否禁用节拍器 切换音源
  686. if ((playState ? playState : state.playState === "paused" ? "play" : "paused") === 'play' && state.modeType === "practise" && state.playMode !== "MIDI") {
  687. console.log("设置音源")
  688. changeSongSourceByBate(metronomeData.disable)
  689. }
  690. // midi播放
  691. if (state.isAppPlay) {
  692. if (playState === "paused") {
  693. await api_cloudSuspend({
  694. songID: state.examSongId,
  695. })
  696. state.playState = 'paused'
  697. return
  698. }
  699. skipNotePlay(state.activeNoteIndex, false);
  700. await api_cloudChangeSpeed({
  701. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  702. originalSpeed: state.originSpeed,
  703. songID: state.examSongId,
  704. });
  705. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  706. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  707. state.playState = status
  708. } else {
  709. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  710. }
  711. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  712. resetPlaybackToStart();
  713. }
  714. // 当在节拍器播放期间暂停的话 就暂停节拍器
  715. if (state.playState === "paused") {
  716. closeTick()
  717. }
  718. // 设置为开始播放时, 如果需要节拍,先播放节拍器 只有在当前播放时间不为0的时候开启节拍器
  719. if (state.playState === "play" && getAudioCurrentTime() === 0 && ((state.playType === "play" && state.needTick) || (state.playType === "sing" && state.needSingTick))) {
  720. // 如果是系统节拍器 等系统节拍器播完了再播,如果是mp3节拍器 直接播
  721. if ((state.playType === "play" && !state.isOpenMetronome) || (state.playType === "sing" && !state.isSingOpenMetronome)) {
  722. const tickend = await handleStartTick();
  723. // console.log("🚀 ~ tickend:", tickend)
  724. // 节拍器返回false, 取消播放
  725. if (!tickend) {
  726. state.playState = "paused";
  727. return false;
  728. }
  729. } else {
  730. handleStartTick()
  731. }
  732. }
  733. // 如果选段没有结束, 直接开始播放,清空选段状态
  734. if (state.playState == "play") {
  735. if (state.sectionStatus && state.section.length < 2) {
  736. clearSelection();
  737. }
  738. }
  739. audioListStart(state.playState);
  740. return true;
  741. };
  742. /** 结束播放 */
  743. export const handleStopPlay = () => {
  744. state.playState = "paused";
  745. audioListStart(state.playState);
  746. };
  747. /** 重置播放为开始 */
  748. export const resetPlaybackToStart = () => {
  749. // 如果为选段状态
  750. if (state.sectionStatus && state.section.length === 2) {
  751. state.section = formateSelectMearure(state.section);
  752. return;
  753. } else {
  754. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  755. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  756. }
  757. skipNotePlay(0, true);
  758. };
  759. /** 跳转到指定音符 */
  760. export const gotoCustomNote = (index: number) => {
  761. try {
  762. state.osmd.cursor.reset();
  763. } catch (error) { }
  764. for (let i = 0; i < index; i++) {
  765. state.osmd.cursor.next();
  766. }
  767. };
  768. // 找出离目标元素最近的音符
  769. const computedDistance = (x: number, y: number) => {
  770. let minDistance = -1, minidx = 0;
  771. let a, b, c;
  772. state.noteCoords.forEach((note: any, idx: any) => {
  773. //a,b为直角三角形的两个直角边
  774. a = Math.abs(note.x - x)
  775. b = Math.abs(note.y - y)
  776. //c为直角三角形的斜边
  777. c = Math.sqrt(a * a + b * b) as 0
  778. c = Number(c.toFixed(0)) as 0
  779. if (c !== 0 && (minDistance === - 1 || c < minDistance)) {
  780. //min为元素中离目标元素最近元素的距离
  781. minDistance = c
  782. minidx = idx
  783. }
  784. })
  785. return minidx
  786. };
  787. const customNotePosition = (note: any, cursor: any) => {
  788. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  789. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  790. const pageLeft = document.getElementById('scrollContainer')?.getBoundingClientRect()?.x || 0;
  791. // 元素的位置
  792. const element = document.getElementById('cursorImg-0')?.getBoundingClientRect?.() || { x: 0, y: 0 };
  793. // 找出距离元素最近的音符
  794. if (element.x && element.y) {
  795. const noteIdx = computedDistance(element.x, element.y);
  796. const targetX = state.noteCoords[noteIdx]?.x - pageLeft;
  797. console.log('音符索引', noteIdx)
  798. cursor.cursorElement.style.left = targetX + "px";
  799. cursor.cursorElement.style.transform = `translateX(0px)`;
  800. }
  801. }
  802. }
  803. const setCursorPosition = (note: any, cursor: any, flag?: string) => {
  804. // console.log('音符',note?.i,state.osmd.Cursor.noteGraphicalId,note.svgElement?.attrs?.id)
  805. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  806. /**
  807. * bug:#9920、#9940
  808. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  809. */
  810. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  811. return
  812. }
  813. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  814. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  815. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  816. const cursorLeft = cursor?.cursorElement?.style?.left ? parseFloat(cursor.cursorElement.style.left) : 0;
  817. let patchX = 0;
  818. if (state.cbsExamSongId == '1788502467554750466') {
  819. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  820. patchX = (note.i == 0 || note.i == 60) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i >= 2 || note.i <= 6) || (note.i >= 8 || note.i <= 22) || (note.i >= 24 || note.i <= 37) || (note.i >= 39 || note.i <= 43) || (note.i >= 45 || note.i <= 51) || (note.i >= 53 || note.i <= 57) || (note.i == 59) ? 6 : 0;
  821. }
  822. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  823. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  824. }
  825. } else if (state.cbsExamSongId == '1788501975122489346') {
  826. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  827. patchX = (note.i == 0) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i == 9 || note.i == 10 || note.i == 12 || note.i == 13) ? 3 : (note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59) ? 6 : (note.i == 45) ? -8 : (note.i >= 15 || note.i <= 29) || (note.i >= 31 || note.i <= 36) || (note.i >= 38 || note.i <= 44) || (note.i >= 46 || note.i <= 50) || (note.i >= 52 || note.i <= 58) || (note.i >= 60 || note.i <= 64) || (note.i == 66) ? 4 : 0;
  828. }
  829. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  830. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  831. }
  832. }
  833. if (flag === 'refresh' || (flag === 'init' && !state.specialPosInit)) {
  834. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  835. cursor.cursorElement.style.left = cursorLeft + patchX + "px";
  836. state.specialPosInit = true;
  837. }
  838. } else {
  839. nextTick(() => {
  840. let bbox = note.bbox;
  841. if (!bbox) {
  842. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  843. x: 0,
  844. y: 0,
  845. };
  846. const parentLeft = musicContainer.x || 0;
  847. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  848. if (noteEle) {
  849. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  850. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  851. if (noteHeadBbox) {
  852. note.bbox = {
  853. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  854. width: noteHeadBbox.width * 1.5,
  855. };
  856. bbox = note.bbox;
  857. }
  858. }
  859. }
  860. if (!bbox) return;
  861. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  862. const width = (bbox.width - baseW) / 3;
  863. // console.log(555555,bbox.left,width)
  864. cursor.cursorElement.style.left = bbox.left + "px";
  865. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  866. });
  867. }
  868. }
  869. };
  870. /**
  871. * 跳转到下一个音符
  872. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  873. **/
  874. export const gotoNext = (note: any, skipNote?: boolean) => {
  875. // console.log(33333333333,state.activeNoteIndex,note.i)
  876. const num = note.i;
  877. if (state.activeNoteIndex === note.i) {
  878. try {
  879. setCursorPosition(note, state.osmd.cursor, 'init');
  880. } catch (error) {
  881. console.log(error);
  882. }
  883. // 重置 或者切换演奏演唱的时候 可能出现 state.activeNoteIndex === note.i的情况 执行
  884. fillWordColor();
  885. if (state.isSingleLine && state.playState === "paused") {
  886. moveSvgDom(skipNote);
  887. }
  888. return;
  889. }
  890. const osmd = state.osmd;
  891. let prev = state.activeNoteIndex;
  892. state.activeNoteIndex = num;
  893. state.activeMeasureIndex = note.MeasureNumberXML;
  894. if (prev && num - prev === 1) {
  895. // console.log('跳转音符',11111,osmd.cursor)
  896. // if (!note.id && note.multipleRestMeasures === 0) {
  897. // } else {
  898. // osmd.cursor.next();
  899. // }
  900. osmd.cursor.next();
  901. } else if (prev && num - prev > 0) {
  902. while (num - prev > 0) {
  903. prev++;
  904. // console.log('跳转音符',22222)
  905. osmd.cursor.next();
  906. }
  907. } else {
  908. gotoCustomNote(num);
  909. }
  910. try {
  911. setCursorPosition(note, state.osmd.cursor, 'refresh');
  912. } catch (error) {
  913. console.log(error);
  914. }
  915. fillWordColor();
  916. // 一行谱,需要滚动小节
  917. if (state.isSingleLine) {
  918. moveSvgDom(skipNote);
  919. }
  920. scrollViewNote();
  921. };
  922. /** 获取指定音符 */
  923. export const getNote = (currentTime: number) => {
  924. const times = state.times;
  925. const len = state.times.length;
  926. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  927. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  928. onEnded();
  929. return;
  930. }
  931. let _item = null as any;
  932. for (let i = state.activeNoteIndex; i < len; i++) {
  933. let item = times[i];
  934. const prevItem = times[i - 1];
  935. // if (state.isEvxml) {
  936. // let diffArr: any[] = [];
  937. // times.forEach((note: any, noteIdx: number) => {
  938. // if (currentTime >= note.time && currentTime <= times[noteIdx+1].time) {
  939. // let diffTime = times[noteIdx+1].time - currentTime;
  940. // diffArr.push({
  941. // diffTime,
  942. // idx: noteIdx
  943. // })
  944. // }
  945. // })
  946. // diffArr.sort((a, b) => a.diffTime - b.diffTime);
  947. // item = diffArr.length ? times[diffArr[0].idx] : item;
  948. // }
  949. if (currentTime >= item.time) {
  950. if (!prevItem || item.time != prevItem.time) {
  951. _item = item;
  952. }
  953. } else {
  954. break;
  955. }
  956. }
  957. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  958. return _item;
  959. };
  960. /** 重播 */
  961. export const handleResetPlay = () => {
  962. // 如果是midi需要重置播放进度
  963. if (state.isAppPlay) {
  964. audioData.progress = 0
  965. }
  966. resetPlaybackToStart();
  967. // 如果是暂停, 直接播放
  968. togglePlay("play");
  969. };
  970. /** 设置速度 */
  971. export const handleSetSpeed = (speed: number) => {
  972. setStorageSpeed(state.examSongId, speed);
  973. state.speed = speed;
  974. };
  975. /** 清除选段状态 */
  976. export const clearSelection = () => {
  977. state.sectionStatus = false;
  978. state.section = [];
  979. closeToast();
  980. };
  981. /** 开启选段 */
  982. export const handleChangeSection = () => {
  983. // 如果开启了选段,再次点击取消选段
  984. if (state.sectionStatus) {
  985. togglePlay("paused");
  986. clearSelection();
  987. skipNotePlay(0, true);
  988. state.sectionFirst = null;
  989. return;
  990. }
  991. state.sectionStatus = true;
  992. // 开启
  993. if (state.sectionStatus) {
  994. togglePlay("paused");
  995. }
  996. showToast({
  997. message: "请选择开始小节",
  998. duration: 0,
  999. position: "top",
  1000. className: "selectionToast",
  1001. });
  1002. };
  1003. /** 效验并格式化选段小节 */
  1004. const formateSelectMearure = (_list: any[]): any[] => {
  1005. if (!_list.length) return [];
  1006. const list = _list.sort((a, b) => a.time - b.time);
  1007. const startXml = list[0]?.measureOpenIndex;
  1008. const endXml = list.last()?.measureOpenIndex;
  1009. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  1010. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  1011. // 没有找到选段小节
  1012. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  1013. clearSelection();
  1014. return [];
  1015. }
  1016. list[0] = selectStartMeasure[0];
  1017. list[1] = selectEndMeasure.last();
  1018. let startItemINdex = list[0].i;
  1019. // 开启预备拍
  1020. if (state.isOpenPrepare) {
  1021. const startXmlIndex = list[0].MeasureNumberXML;
  1022. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  1023. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  1024. }
  1025. skipNotePlay(startItemINdex, startItemINdex === 0);
  1026. return list;
  1027. };
  1028. /** 选择选段 */
  1029. export const handleSelection = (item: any) => {
  1030. if (!state.sectionStatus || state.section.length > 1) return;
  1031. if (state.section.length !== 2 && item) {
  1032. state.section.push(item);
  1033. if (state.section.length === 2) {
  1034. setSection(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  1035. //state.section = formateSelectMearure(state.section);
  1036. closeToast();
  1037. }
  1038. }
  1039. if (state.section.length === 1) {
  1040. showToast({
  1041. message: "请选择结束小节",
  1042. duration: 0,
  1043. position: "top",
  1044. className: "selectionToast",
  1045. });
  1046. }
  1047. };
  1048. /** 阶段练习、阶段评测设置选段小节 */
  1049. export const setSection = (start: number, end: number, userSpeed?: number) => {
  1050. const startNotes = state.times.filter(
  1051. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  1052. )
  1053. const endNotes = state.times.filter(
  1054. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  1055. )
  1056. state.userChooseEndIndex = end
  1057. const lastEndId = endNotes[endNotes.length - 1].noteId
  1058. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  1059. // 是否符合重播规则
  1060. const canRepeatInfo = verifyCanRepeat(start, end)
  1061. console.log('能否重播', canRepeatInfo)
  1062. const isCanRepeat = canRepeatInfo.canRepeat
  1063. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1064. /**
  1065. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  1066. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  1067. * TODO:通过vf-volta判断是否是跳房子
  1068. */
  1069. let isSkipVolta = false; // 结束小节是否是跳房子小节
  1070. if (lastEndNotes.length === 1) {
  1071. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  1072. }
  1073. let currentEndNum: number = end
  1074. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  1075. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  1076. currentEndNum = currentEndNum - 1
  1077. const newEndNotes = state.times.filter(
  1078. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  1079. )
  1080. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  1081. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  1082. }
  1083. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  1084. const startNote = startNotes[0]
  1085. // const endNote = endNotes[endNotes.length - 1]
  1086. const endNote = lastEndNotes[endIdx]
  1087. if (startNote && endNote) {
  1088. state.isSelectMeasureMode = true;
  1089. // 设置小节
  1090. hanldeDirectSelection([startNote, endNote]);
  1091. //设置速度
  1092. if (userSpeed) {
  1093. handleSetSpeed(userSpeed);
  1094. }
  1095. }
  1096. }
  1097. /** 直接设置选段 */
  1098. export const hanldeDirectSelection = (list: any[]) => {
  1099. if (!Array.isArray(list) || list.length !== 2) return;
  1100. state.sectionStatus = true;
  1101. setTimeout(() => {
  1102. state.section = formateSelectMearure(list);
  1103. console.log('选段小节', state.section)
  1104. }, 0);
  1105. };
  1106. let offsetTop = 0;
  1107. /**
  1108. * 窗口内滚动到音符的区域
  1109. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  1110. * @returns void
  1111. */
  1112. export const scrollViewNote = () => {
  1113. const cursorElement = document.getElementById("cursorImg-0")!;
  1114. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  1115. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  1116. offsetTop = cursorElement.offsetTop;
  1117. if (offsetTop > 50) {
  1118. musicAndSelection.scrollTo({
  1119. top: (offsetTop - 50) * state.musicZoom,
  1120. behavior: "smooth",
  1121. });
  1122. } else {
  1123. musicAndSelection.scrollTo({
  1124. top: 0,
  1125. behavior: "smooth",
  1126. });
  1127. }
  1128. };
  1129. /** 检测是否是节奏练习 */
  1130. export const isRhythmicExercises = () => {
  1131. return state.examSongName.indexOf("节奏练习") > -1;
  1132. };
  1133. /** 重置状态 */
  1134. export const handleRessetState = () => {
  1135. // 切换模式,清除选段
  1136. clearSelection();
  1137. skipNotePlay(0, true);
  1138. // midi 重置播放进度
  1139. if (state.isAppPlay) {
  1140. audioData.progress = 0;
  1141. }
  1142. if (state.modeType === "evaluating") {
  1143. handleStartEvaluat();
  1144. } else if (state.modeType === "practise") {
  1145. togglePlay("paused");
  1146. } else if (state.modeType === "follow") {
  1147. toggleFollow(false);
  1148. }
  1149. };
  1150. export default state;
  1151. /** 初始化评测音频 */
  1152. export const evaluatCreateMusicPlayer = () => {
  1153. return api_createMusicPlayer({
  1154. musicSrc: state.accompany || state.music, // 曲谱音频url
  1155. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1156. });
  1157. };
  1158. /** 获取内容平台的接口详情并初始化state信息 */
  1159. export const getMusicDetail = async (id: string) => {
  1160. const res = await getMusicSheetDetail(id);
  1161. if (res?.code === 200) {
  1162. await getMusicInfo(res)
  1163. }
  1164. };
  1165. const getMusicInfo = async (res: any) => {
  1166. const xmlString = await fetch(res.data.xmlFileUrl).then((response) => response.text());
  1167. downloadXmlStr.value = xmlString //给musice-score 赋值xmlString 以免加载2次
  1168. const tracks = xmlToTracks(xmlString) //获取声轨列表
  1169. let index = query["part-index"] ? parseInt(query["part-index"]) : 0
  1170. const musicObj = initMusicSource(res.data, tracks[index]) //当前part-index找不到声源的时候以第一个为准
  1171. index = tracks.findIndex(item => { // 筛选出当前的index
  1172. return item === musicObj?.track
  1173. })
  1174. const musicInfo = {
  1175. ...res.data,
  1176. track: musicObj?.track
  1177. };
  1178. console.log("🚀 ~ musicInfo:", musicInfo);
  1179. setState(musicInfo, index);
  1180. };
  1181. //获取xml中的音轨数据
  1182. function xmlToTracks(xmlString: string) {
  1183. const xmlParse = new DOMParser().parseFromString(xmlString, "text/xml");
  1184. const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
  1185. return partNames.reduce((arr: string[], item) => {
  1186. const textContent = item?.textContent?.trim()
  1187. if (textContent !== "COMMON" && textContent) {
  1188. arr.push(textContent)
  1189. }
  1190. return arr
  1191. }, []);
  1192. }
  1193. // 设置音源
  1194. function initMusicSource(data: any, track?: string) {
  1195. const { instrumentId } = storeData.user
  1196. let { musicSheetType, isAllSubject, musicSheetSoundList, musicSheetAccompanimentList } = data
  1197. musicSheetSoundList || (musicSheetSoundList = [])
  1198. musicSheetAccompanimentList || (musicSheetAccompanimentList = [])
  1199. let musicObj, accompanyObj, fanSongObj, banSongObj
  1200. // 独奏
  1201. if (musicSheetType === "SINGLE") {
  1202. // 适用声部(instrumentId)为true 时候没有乐器只有一个原音;当前用户有乐器就匹配 不然取第一个原音
  1203. musicObj = musicSheetSoundList.find((item: any) => {
  1204. return (isAllSubject || !instrumentId) ? item.audioPlayType === "PLAY" : (item.audioPlayType === "PLAY" && item.musicalInstrumentId == instrumentId)
  1205. })
  1206. // 因为可能根据学生的乐器id也找不到曲目所以尝试取第一个
  1207. musicObj || (musicObj = musicSheetSoundList.find((item: any) => {
  1208. return item.audioPlayType === "PLAY"
  1209. }))
  1210. fanSongObj = musicSheetSoundList.find((item: any) => {
  1211. return item.audioPlayType === "SING"
  1212. })
  1213. banSongObj = musicSheetAccompanimentList.find((item: any) => {
  1214. return item.audioPlayType === "SING"
  1215. })
  1216. } else {
  1217. // 合奏 合奏根据声轨来区分原音
  1218. musicObj = track ? musicSheetSoundList.find((item: any) => {
  1219. return item.track === track
  1220. }) : musicSheetSoundList[0]
  1221. }
  1222. accompanyObj = musicSheetAccompanimentList.find((item: any) => {
  1223. return item.audioPlayType === "PLAY"
  1224. })
  1225. // 当没有任何曲目的时候报错
  1226. if (!musicObj?.audioFileUrl && !accompanyObj?.audioFileUrl && !fanSongObj?.audioFileUrl && !banSongObj?.audioFileUrl && !fanSongObj?.solmizationFileUrl) {
  1227. throw new Error("该曲目无任何音源");
  1228. }
  1229. Object.assign(state, {
  1230. music: musicObj?.audioFileUrl,
  1231. accompany: accompanyObj?.audioFileUrl,
  1232. fanSong: fanSongObj?.audioFileUrl,
  1233. banSong: banSongObj?.audioFileUrl,
  1234. mingSong: fanSongObj?.solmizationFileUrl
  1235. })
  1236. Object.assign(state.beatSong, {
  1237. music: musicObj?.audioBeatMixUrl,
  1238. accompany: accompanyObj?.audioBeatMixUrl,
  1239. fanSong: fanSongObj?.audioBeatMixUrl,
  1240. banSong: banSongObj?.audioBeatMixUrl,
  1241. mingSong: fanSongObj?.solmizationBeatUrl
  1242. })
  1243. return musicObj
  1244. }
  1245. const setState = (data: any, index: number) => {
  1246. state.appName = "COLEXIU";
  1247. state.detailId = data.bizId;
  1248. state.xmlUrl = data.xmlFileUrl;
  1249. state.paymentType = data.paymentType
  1250. state.partIndex = index;
  1251. state.trackId = data.track;
  1252. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1253. // 声部code
  1254. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1255. // 乐器code
  1256. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1257. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1258. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1259. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1260. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1261. state.categoriesId = data.musicCategoryId;
  1262. state.categoriesName = data.musicTagNames;
  1263. // state.enableEvaluation = data.isEvaluated ? true : false;
  1264. state.examSongId = data.bizId + "";
  1265. state.cbsExamSongId = data.id + "";
  1266. state.examSongName = data.name;
  1267. state.coverImg = data.musicCover ?? "";
  1268. // 单声部多声轨合并展示
  1269. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1270. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1271. // 解析扩展字段
  1272. if (data.extConfigJson) {
  1273. try {
  1274. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1275. } catch (error) {
  1276. console.error("解析扩展字段错误:", error);
  1277. }
  1278. }
  1279. state.gradualTimes = state.extConfigJson.gradualTimes;
  1280. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1281. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1282. // 是否开启节拍器
  1283. state.needTick = !!data.isPlayBeat
  1284. state.needSingTick = !!data.isPlaySingBeat
  1285. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1286. // 演奏模式是否播mp3节拍器
  1287. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1288. // 演唱模式是否播mp3节拍器
  1289. state.isSingOpenMetronome = data.isPlaySingBeat && !data.isUseSingSystemBeat ? true : false
  1290. state.isShowFingering = data.isShowFingering ? true : false;
  1291. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1292. state.isAppPlay = data.playMode === 'MIDI';
  1293. state.midiUrl = data.midiFileUrl;
  1294. state.parentCategoriesId = data.musicTag;
  1295. state.musicSheetCategoriesId = data.musicCategoryId;
  1296. state.bizMusicCategoryId = data.bizMusicCategoryId
  1297. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1298. state.originSpeed = state.speed = parseFloat(data.playSpeed) || 0;
  1299. // state.originSpeed = state.speed = data.playSpeed;
  1300. // state.playIngSpeed = data.playSpeed;
  1301. const track = data.code || data.track;
  1302. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1303. // 能否评测,根据当前声轨有无伴奏判断
  1304. // if (state.isAppPlay) {
  1305. // state.enableEvaluation = state.midiUrl ? true : false
  1306. // } else {
  1307. // state.enableEvaluation = state.accompany ? true : false
  1308. // }
  1309. state.enableEvaluation = true
  1310. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1311. // multiTracksSelection 返回为空,默认代表全部分轨
  1312. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1313. // 开启预备小节
  1314. state.isOpenPrepare = true;
  1315. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1316. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1317. // 是否打击乐
  1318. /**
  1319. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1320. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1321. * 打击乐&节奏练习,没有跟练模式
  1322. */
  1323. // state.isPercussion = isRhythmicExercises();
  1324. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1325. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1326. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1327. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1328. // 设置指法
  1329. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1330. /**
  1331. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1332. * 获取指法code
  1333. */
  1334. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1335. state.fingeringInfo = subjectFingering(code);
  1336. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1337. state.musicalCodeId = state.fingeringInfo?.id || 0
  1338. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1339. ; (window as any).DYSubjectId = state.musicalCodeId
  1340. // 开启自定义每行显示的小节数
  1341. ; (window as any).customSectionAmount = true
  1342. // 标识是课堂乐器,用于移调时进行区分处理
  1343. ; (window as any).DYProjectName = 'musicScore';
  1344. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1345. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1346. state.setting.displayFingering = false
  1347. }
  1348. // 如果是PC端,放大曲谱
  1349. state.platform = query.platform?.toLocaleUpperCase() || "";
  1350. if (state.platform === IPlatform.PC) {
  1351. state.zoom = query.zoom || 1.5;
  1352. state.enableEvaluation = false;
  1353. }
  1354. /**
  1355. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1356. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1357. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1358. *
  1359. */
  1360. let pitchTrack = null
  1361. if (state.isConcert) {
  1362. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1363. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1364. } else {
  1365. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1366. }
  1367. let musicalRenderType = ''
  1368. if (pitchTrack?.defaultScore) {
  1369. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1370. }
  1371. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1372. /**
  1373. * TODO:摇篮曲特殊处理
  1374. */
  1375. if (['1788501975122489346', '1788502467554750466', '1789839575249596417'].includes(state.cbsExamSongId)) {
  1376. if (state.musicRenderType === 'fixedTone') {
  1377. state.musicRenderType = EnumMusicRenderType.firstTone;
  1378. }
  1379. }
  1380. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1381. console.log("state对象", state);
  1382. // 评测基准频率
  1383. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1384. state.baseFrequency = Number(state.baseFrequency)
  1385. // 用户上次的频率和基准频率误差超过10,则重置
  1386. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1387. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1388. } else {
  1389. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1390. }
  1391. };
  1392. // 多分轨合并显示标示
  1393. const setCustom = (trackNum?: number) => {
  1394. if (trackNum || state.extConfigJson.multitrack) {
  1395. state.multitrack = trackNum || 0
  1396. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1397. }
  1398. };
  1399. /** 跟练模式播放节拍器(叮咚) */
  1400. export const followBeatPaly = () => {
  1401. let metroTimer: any = null;
  1402. if (!followData.start) {
  1403. clearTimeout(metroTimer)
  1404. metroTimer = null
  1405. return;
  1406. }
  1407. const time = state.measureTime * 1000 / metronomeData.totalNumerator
  1408. requestAnimationFrame(() => {
  1409. const endTime = Date.now();
  1410. if (endTime - state.beatStartTime < time) {
  1411. followBeatPaly();
  1412. } else {
  1413. // metroTimer = setTimeout(() => {
  1414. // metronomeData.metro?.simulatePlayAudio()
  1415. // startTime = Date.now();
  1416. // followBeatPaly();
  1417. // }, time);
  1418. metronomeData.metro?.simulatePlayAudio()
  1419. state.beatStartTime = Date.now();
  1420. followBeatPaly();
  1421. }
  1422. });
  1423. };
  1424. // 音符添加bbox
  1425. export const addNoteBBox = (list: any[]) => {
  1426. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  1427. x: 0,
  1428. y: 0,
  1429. };
  1430. const parentLeft = musicContainer.x || 0;
  1431. let voicesBBox: any = null;
  1432. for (let i = 0; i < list.length; i++) {
  1433. const note = list[i];
  1434. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1435. /**
  1436. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1437. */
  1438. let bbox: any = null;
  1439. if (svgElement?.attrs.id) {
  1440. // @ts-ignore
  1441. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1442. const noteBbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBoundingClientRect?.() || { x: 0, width: 0 };
  1443. bbox = {
  1444. left: noteBbox.x - parentLeft - noteBbox.width / 4, // 用于简谱模式,跳动音符时,设置光标的位置(五线谱:osmd自动设置光标位置,简谱:需要手动设置光标位置)
  1445. x: bbox?.x * state.zoom,
  1446. y: bbox?.y * state.zoom,
  1447. width: bbox?.width * state.zoom,
  1448. height: bbox?.height * state.zoom,
  1449. }
  1450. } else {
  1451. // @ts-ignore
  1452. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1453. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1454. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1455. currentVoicesBBox = voicesBBox;
  1456. }
  1457. let nextIndex = i + 1;
  1458. while (!list[nextIndex]?.id && nextIndex < list.length) {
  1459. nextIndex += 1;
  1460. }
  1461. // 休止小节的开头和下一个音符之间的间距
  1462. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1463. if (list[nextIndex]?.id) {
  1464. // @ts-ignore
  1465. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1466. }
  1467. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1468. bbox = currentVoicesBBox ? {
  1469. bottom: currentVoicesBBox.bottom,
  1470. height: 30,
  1471. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1472. right: currentVoicesBBox.y,
  1473. top: currentVoicesBBox.top,
  1474. width: 1,
  1475. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1476. y: currentVoicesBBox.y,
  1477. svgBodyLeft: svgBodyBBox?.x,
  1478. } : null;
  1479. voicesBBox = currentVoicesBBox;
  1480. }
  1481. // todo 连续修止小节bug
  1482. note.bbox = bbox;
  1483. }
  1484. }
  1485. // 给歌词和音符添加动态颜色
  1486. const fillWordColor = () => {
  1487. // console.log('当前音符',state.activeNoteIndex)
  1488. state.times.forEach((item: any, idx: number) => {
  1489. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1490. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1491. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1492. svgEl?.classList.add('noteActive')
  1493. stemEl?.classList.add('noteActive')
  1494. } else {
  1495. svgEl?.classList.remove('noteActive')
  1496. stemEl?.classList.remove('noteActive')
  1497. }
  1498. })
  1499. // 给当前匹配到的歌词添加颜色
  1500. const currentNote = state.times[state.activeNoteIndex];
  1501. const lyrics: SVGAElement[] = Array.from(document.querySelectorAll(".vf-lyric"));
  1502. lyrics.forEach((lyric) => {
  1503. lyric?.classList.remove('lyricActive')
  1504. })
  1505. const currentLyrics: SVGAElement[] = Array.from(document.querySelectorAll(`.lyric${currentNote?.noteId}`));
  1506. currentLyrics.forEach((lyric, index) => {
  1507. if (index === currentNote.repeatIdx) {
  1508. lyric?.classList.add('lyricActive')
  1509. }
  1510. })
  1511. }
  1512. /** 跳动svgdom */
  1513. export const moveSvgDom = (skipNote?: boolean) => {
  1514. /**
  1515. * 计算需要移动的距离
  1516. * 当前选中的音符和第一个音符之间的间距
  1517. */
  1518. if (skipNote) {
  1519. 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;
  1520. // 点击 清空translateXNum
  1521. smoothAnimationState.translateXNum = 0
  1522. moveSmoothAnimation(0, state.activeNoteIndex)
  1523. smoothAnimationState.osdmScrollDom!.scrollTo({
  1524. left: distance,
  1525. behavior: "smooth",
  1526. });
  1527. }
  1528. }
  1529. // 暂停的时候 恢复一行谱偏移位置信息
  1530. watch(
  1531. () => state.playState,
  1532. () => {
  1533. if (state.isSingleLine) {
  1534. // 当在播放中暂停 执行这个方法
  1535. if (!state.playEnd && state.playState === "paused") {
  1536. moveTranslateXNum(0)
  1537. const scrollLeft = smoothAnimationState.osdmScrollDom!.scrollLeft
  1538. smoothAnimationState.osdmScrollDom!.scrollLeft = scrollLeft + smoothAnimationState.translateXNum
  1539. smoothAnimationState.translateXNum = 0
  1540. }
  1541. }
  1542. }
  1543. )
  1544. /* 根据当前的小节获取前面有多少需要去除的合并小节 */
  1545. function getNeedReduceMultipleRestNum(currMeasureIndex: number) {
  1546. let needReduceMultipleRestNum = 0;
  1547. for (let noteIndex = 0; noteIndex < state.times.length; noteIndex++) {
  1548. const note = state.times[noteIndex];
  1549. if (note.MeasureNumberXML > currMeasureIndex) {
  1550. break;
  1551. }
  1552. if (note.multipleRestMeasures && note.multipleRestMeasures > 1) {
  1553. needReduceMultipleRestNum += 1;
  1554. }
  1555. }
  1556. return needReduceMultipleRestNum
  1557. }
  1558. watch(
  1559. () => state.activeMeasureIndex,
  1560. () => {
  1561. // 需要减去的合并小节数
  1562. const needReduceMultipleRestNum = getNeedReduceMultipleRestNum(state.activeMeasureIndex)
  1563. const matchMeasureNum = state.activeMeasureIndex - needReduceMultipleRestNum - 1
  1564. console.log('选中的小节', matchMeasureNum, '需要减去的小节', needReduceMultipleRestNum, '当前的小节', state.activeMeasureIndex)
  1565. state.vfmeasures.forEach((item: any, idx: number) => {
  1566. if (idx === matchMeasureNum) {
  1567. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#132D4C")
  1568. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#040D1E")
  1569. } else {
  1570. // 有选段只清除选段处的
  1571. if (state.section.length === 2) {
  1572. // 把中间置灰
  1573. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  1574. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  1575. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  1576. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  1577. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  1578. }
  1579. const leftVfmeasuresIndex = leftMeasureNumberXML - getNeedReduceMultipleRestNum(leftMeasureNumberXML) - 1
  1580. const rightVfmeasuresIndex = rightMeasureNumberXML - getNeedReduceMultipleRestNum(rightMeasureNumberXML) - 1
  1581. if (idx >= leftVfmeasuresIndex && idx <= rightVfmeasuresIndex) {
  1582. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1583. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1584. }
  1585. // 预备小节
  1586. if (state.sectionFirst) {
  1587. const sectionFirstVfmeasuresIndex = state.sectionFirst.MeasureNumberXML - getNeedReduceMultipleRestNum(state.sectionFirst.MeasureNumberXML) - 1
  1588. const sectionFirstDom = state.vfmeasures[sectionFirstVfmeasuresIndex]
  1589. sectionFirstDom?.querySelector('.vf-custom-bg')?.setAttribute("fill", "#71B8BD")
  1590. sectionFirstDom?.querySelector('.vf-custom-bot')?.setAttribute("fill", "#448F9C")
  1591. }
  1592. } else {
  1593. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1594. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1595. }
  1596. }
  1597. })
  1598. }
  1599. );
  1600. watch(
  1601. () => state.section,
  1602. () => {
  1603. if (state.section.length === 2) {
  1604. // 把前面和 后面置灰
  1605. let leftMeasureNumberXML = state.section[0].MeasureNumberXML
  1606. let rightMeasureNumberXML = state.section[1].MeasureNumberXML
  1607. if (leftMeasureNumberXML > rightMeasureNumberXML) {
  1608. leftMeasureNumberXML = state.section[1].MeasureNumberXML
  1609. rightMeasureNumberXML = state.section[0].MeasureNumberXML
  1610. }
  1611. const leftVfmeasuresIndex = leftMeasureNumberXML - getNeedReduceMultipleRestNum(leftMeasureNumberXML) - 1
  1612. const rightVfmeasuresIndex = rightMeasureNumberXML - getNeedReduceMultipleRestNum(rightMeasureNumberXML) - 1
  1613. state.vfmeasures.forEach((item: any, idx: number) => {
  1614. // 小于选中置灰
  1615. if (idx < leftVfmeasuresIndex) {
  1616. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(96,159,207,0.5)")
  1617. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "rgba(43,112,165,0.5)")
  1618. }
  1619. // 大于选中置灰
  1620. if (idx > rightVfmeasuresIndex) {
  1621. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "rgba(96,159,207,0.5)")
  1622. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "rgba(43,112,165,0.5)")
  1623. }
  1624. })
  1625. // 预备小节
  1626. if (state.sectionFirst) {
  1627. const sectionFirstVfmeasuresIndex = state.sectionFirst.MeasureNumberXML - getNeedReduceMultipleRestNum(state.sectionFirst.MeasureNumberXML) - 1
  1628. const sectionFirstDom = state.vfmeasures[sectionFirstVfmeasuresIndex]
  1629. sectionFirstDom?.querySelector('.vf-custom-bg')?.setAttribute("fill", "#71B8BD")
  1630. sectionFirstDom?.querySelector('.vf-custom-bot')?.setAttribute("fill", "#448F9C")
  1631. }
  1632. } else {
  1633. // 恢复选段前
  1634. const matchMeasureNum = state.activeMeasureIndex - getNeedReduceMultipleRestNum(state.activeMeasureIndex) - 1
  1635. state.vfmeasures.forEach((item: any, idx: number) => {
  1636. if (idx === matchMeasureNum) {
  1637. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#132D4C")
  1638. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#040D1E")
  1639. } else {
  1640. item.querySelector('.vf-custom-bg')?.setAttribute("fill", "#609FCF")
  1641. item.querySelector('.vf-custom-bot')?.setAttribute("fill", "#2B70A5")
  1642. }
  1643. })
  1644. }
  1645. }
  1646. )
  1647. /** 刷新谱面 */
  1648. export const refreshMusicSvg = () => {
  1649. state.loadingText = '正在加载中,请稍等…'
  1650. if (state.isSingleLine) {
  1651. // 销毁旋律线
  1652. destroySmoothAnimation()
  1653. }
  1654. musicScoreRef.value?.refreshMusicScore()
  1655. }
  1656. // 指法改变显示的时候 osdmScrollDomWith 宽度会变化 所以指法改变的时候这个宽度重新计算
  1657. watch(
  1658. () => state.setting.displayFingering,
  1659. () => {
  1660. nextTick(() => {
  1661. if (smoothAnimationState.osdmScrollDom) {
  1662. smoothAnimationState.osdmScrollDomWith = smoothAnimationState.osdmScrollDom.offsetWidth | 0
  1663. }
  1664. })
  1665. }
  1666. )