state.ts 85 KB

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