state.ts 88 KB

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