state.ts 90 KB

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