state.ts 83 KB

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