state.ts 75 KB

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