state.ts 83 KB

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