state.ts 80 KB

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