state.ts 79 KB

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