state.ts 64 KB

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