state.ts 63 KB

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