state.ts 83 KB

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