state.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. import { closeToast, showToast } from "vant";
  2. import { nextTick, reactive } 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 } 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 } from "/src/view/follow-practice/index"
  17. const query: any = getQuery();
  18. /** 入门 | 进阶 | 大师 */
  19. export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
  20. /** 渲染类型: 五线谱,简谱 */
  21. export enum EnumMusicRenderType {
  22. /** 五线谱 */
  23. staff = "staff",
  24. /** 简谱 */
  25. firstTone = "firstTone",
  26. /** 固定音高 */
  27. fixedTone = "fixedTone",
  28. }
  29. export const musicscoresettingKey = "musicscoresetting";
  30. /** 有声音的是那个音源 */
  31. export type IPlayState = "music" | "background";
  32. /** 播放状态 */
  33. export type IAudioState = "play" | "paused";
  34. /** 来源 */
  35. export enum IPlatform {
  36. APP = "APP",
  37. PC = "PC",
  38. }
  39. export type ISonges = {
  40. background?: string
  41. music?: string
  42. }
  43. /**
  44. * 特殊教材分类id
  45. */
  46. 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
  47. // 乐器code码
  48. export const musicalInstrumentCodeInfo = [
  49. {
  50. name: '长笛',
  51. code: 'Flute',
  52. id: 1
  53. },
  54. {
  55. name: '短笛',
  56. code: 'Piccolo',
  57. id: 2
  58. },
  59. {
  60. name: '单簧管',
  61. code: 'Clarinet',
  62. id: 3
  63. },
  64. {
  65. name: '低音单簧管',
  66. code: 'Bass Clarinet',
  67. id: 4
  68. },
  69. {
  70. name: '中音萨克斯',
  71. code: 'Alto Saxophone',
  72. id: 5
  73. },
  74. {
  75. name: '次中音萨克斯',
  76. code: 'Tenor Saxophone',
  77. id: 6
  78. },
  79. {
  80. name: '高音萨克斯',
  81. code: 'Soprano Saxophone',
  82. id: 7
  83. },
  84. {
  85. name: '上低音萨克斯',
  86. code: 'Baritone Saxophone',
  87. id: 8
  88. },
  89. {
  90. name: '双簧管',
  91. code: 'Oboe',
  92. id: 9
  93. },
  94. {
  95. name: '大管',
  96. code: 'Bassoon',
  97. id: 10
  98. },
  99. {
  100. name: '小号',
  101. code: 'Trumpet',
  102. id: 11
  103. },
  104. {
  105. name: '圆号',
  106. code: 'Horn',
  107. id: 12
  108. },
  109. {
  110. name: '长号',
  111. code: 'Trombone',
  112. id: 13
  113. },
  114. {
  115. name: '上低音号',
  116. code: 'Baritone',
  117. id: 14
  118. },
  119. {
  120. name: '次中音号',
  121. code: 'Euphonium',
  122. id: 15
  123. },
  124. {
  125. name: '大号',
  126. code: 'Tuba',
  127. id: 16
  128. },
  129. {
  130. name: '钢琴',
  131. code: 'Piano',
  132. id: 17
  133. },
  134. {
  135. name: '电钢琴',
  136. code: 'Electronical Piano',
  137. id: 18
  138. },
  139. {
  140. name: '钢片琴',
  141. code: 'Glockenspiel',
  142. id: 19
  143. },
  144. {
  145. name: '小提琴',
  146. code: 'Violin',
  147. id: 20
  148. },
  149. {
  150. name: '中提琴',
  151. code: 'Viola',
  152. id: 21
  153. },
  154. {
  155. name: '大提琴',
  156. code: 'Violoncello',
  157. id: 22
  158. },
  159. {
  160. name: '低音提琴',
  161. code: 'Contrabass',
  162. id: 23
  163. },
  164. {
  165. name: '架子鼓',
  166. code: 'Drum Set',
  167. id: 24
  168. },
  169. {
  170. name: '小鼓',
  171. code: 'Snare Drum',
  172. id: 25
  173. },
  174. {
  175. name: '马林巴',
  176. code: 'Marimba',
  177. id: 26
  178. },
  179. {
  180. name: '颤音琴',
  181. code: 'Vibraphone',
  182. id: 27
  183. },
  184. {
  185. name: '钟琴',
  186. code: 'Chimes',
  187. id: 28
  188. },
  189. {
  190. name: '木琴',
  191. code: 'Xylophone',
  192. id: 29
  193. },
  194. {
  195. name: '管钟',
  196. code: 'Tubular Bells',
  197. id: 30
  198. },
  199. {
  200. name: '定音鼓',
  201. code: 'Timpani',
  202. id: 31
  203. },
  204. {
  205. name: '键盘',
  206. code: 'Mallets',
  207. id: 32
  208. },
  209. {
  210. name: '排箫',
  211. code: 'Panpipes',
  212. id: 33
  213. },
  214. {
  215. name: '陶笛',
  216. code: 'Ocarina',
  217. id: 34
  218. },
  219. {
  220. name: '葫芦丝',
  221. code: 'Woodwind',
  222. id: 35
  223. },
  224. {
  225. name: '口风琴',
  226. code: 'Nai',
  227. id: 36
  228. },
  229. {
  230. name: '德式竖笛',
  231. code: 'Tenor Recorder',
  232. id: 37
  233. },
  234. {
  235. name: '英式竖笛',
  236. code: 'Baroque Recorder',
  237. id: 38
  238. },
  239. {
  240. name: '高音陶笛',
  241. code: 'Whistling',
  242. id: 39
  243. },
  244. ]
  245. const state = reactive({
  246. /** 来源 : PC , app */
  247. platform: "" as IPlatform,
  248. appName: "" as "GYM" | "COLEXIU",
  249. musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
  250. /**曲谱是否渲染完成 */
  251. musicRendered: false,
  252. /** 当前曲谱数据ID, 和曲谱ID不一致 */
  253. detailId: "",
  254. /** 曲谱资源URL */
  255. xmlUrl: "",
  256. /** 声部ID */
  257. subjectId: 0 as number,
  258. trackId: 0 as string | number,
  259. /** 分类ID */
  260. categoriesId: 0,
  261. /** 分类名称 */
  262. categoriesName: "",
  263. /** 是否支持评测 */
  264. enableEvaluation: true,
  265. /** 是否支持转谱 */
  266. enableNotation: false,
  267. /** 曲谱ID */
  268. examSongId: "",
  269. /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
  270. cbsExamSongId: "",
  271. /** 曲谱名称 */
  272. examSongName: "",
  273. /** 曲谱封面 */
  274. coverImg: "",
  275. /** 扩展字段 */
  276. extConfigJson: {} as any,
  277. /** 扩展样式字段 */
  278. extStyleConfigJson: {} as any,
  279. /** 是否开启节拍器(mp3节拍器) */
  280. isOpenMetronome: false,
  281. /** 是否显示指法 */
  282. isShowFingering: false,
  283. /** 原音 */
  284. music: "",
  285. /** 伴奏 */
  286. accompany: "",
  287. /** midiURL */
  288. midiUrl: "",
  289. /** 父分ID */
  290. parentCategoriesId: 0,
  291. /** 分类ID */
  292. musicSheetCategoriesId: 0,
  293. /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
  294. bizMusicCategoryId: 0,
  295. /** 资源类型: mp3 | midi */
  296. playMode: "MP3" as "MP3" | "MIDI",
  297. /** 设置的速度 */
  298. speed: 0,
  299. /** 曲谱音频正常的速度 */
  300. originSpeed: 0,
  301. /** 播放过程中显示的速度 */
  302. playIngSpeed: 0,
  303. /** 分轨名称 */
  304. track: "",
  305. /** 当前显示声部索引 */
  306. partIndex: 0,
  307. /** 是否需要节拍器 */
  308. needTick: false,
  309. /** 曲谱实例 */
  310. osmd: null as unknown as OpenSheetMusicDisplay,
  311. /**是否是特殊乐谱类型, 主要针对管乐迷 */
  312. isSpecialBookCategory: false,
  313. /** 播放状态 */
  314. playState: "paused" as IAudioState,
  315. /** 播放结束状态 */
  316. playEnd: false,
  317. /** 播放那个: 原音,伴奏 */
  318. playSource: "music" as IPlayState,
  319. /** 播放进度 */
  320. playProgress: 0,
  321. /** 激活的note index */
  322. activeNoteIndex: 0,
  323. /** 激活的小节 */
  324. activeMeasureIndex: 0,
  325. /** 选段状态 */
  326. sectionStatus: false,
  327. /** 选段数据 */
  328. section: [] as any[],
  329. /** 选段背景 */
  330. sectionBoundingBoxs: [] as any[],
  331. /** 开启选段预备 */
  332. isOpenPrepare: false,
  333. /** 选段预备 */
  334. sectionFirst: null as any,
  335. /** 音符数据 */
  336. times: [] as any[],
  337. /** 播放模式 */
  338. modeType: "practise" as "practise" | "follow" | "evaluating",
  339. /** 设置 */
  340. setting: {
  341. /** 效音提醒 */
  342. soundEffect: true,
  343. /** 护眼模式 */
  344. eyeProtection: false,
  345. /** 摄像头 */
  346. camera: false,
  347. /** 摄像头透明度 */
  348. cameraOpacity: 70,
  349. /** 循环播放 */
  350. repeatAutoPlay: true,
  351. /** 显示指法 */
  352. displayFingering: true,
  353. /** 显示光标 */
  354. displayCursor: true,
  355. /** 频率 */
  356. frequency: 0,
  357. /** 评测难度 */
  358. evaluationDifficulty: "BEGINNER" as IDifficulty,
  359. /** 保存到相册 */
  360. saveToAlbum: true,
  361. /** 开启伴奏 */
  362. enableAccompaniment: true,
  363. /** 反应时间 */
  364. reactionTimeMs: 0,
  365. /** 节拍器音量 */
  366. beatVolume: 50,
  367. },
  368. /** 后台设置的基准评测频率 */
  369. baseFrequency: 440,
  370. /** mp3节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
  371. fixtime: 0,
  372. /** evxml等待播放的时间 */
  373. evXmlBeginTime: 0,
  374. /** 指法信息 */
  375. fingeringInfo: {} as IFingering,
  376. /** 滚动容器的ID */
  377. scrollContainer: "musicAndSelection",
  378. /** 是否是打击乐 */
  379. isPercussion: false,
  380. /** 评测标准 */
  381. evaluationStandard: '',
  382. /** 是否重复节拍器的时间 */
  383. repeatedBeats: 0,
  384. /**当前曲谱中所有声部名字 */
  385. partListNames: [] as any,
  386. /** 渐变速度信息 */
  387. gradual: [] as GradualNote[],
  388. /** 渐变速度版本 */
  389. gradualVersion: GradualVersion.BASE as GradualVersion,
  390. /** 渐变时间信息 */
  391. gradualTimes: null as GradualTimes,
  392. /** 单声部多声轨 */
  393. multitrack: 0,
  394. /** 缩放 */
  395. zoom: 0.8,
  396. /** 渲染曲谱比例 */
  397. musicZoom: 1,
  398. /** 练习,评测是否是选段模式 */
  399. isSelectMeasureMode: false,
  400. /** 是否是评分显示 */
  401. isReport: false,
  402. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  403. isHideEvaluatReportSaveBtn: false,
  404. /** 是否是合奏 */
  405. isConcert: false,
  406. /** 用户选择的结束小节数 */
  407. userChooseEndIndex: 0,
  408. /** 重播小节集合信息 */
  409. repeatInfo: [] as any,
  410. /** 多分轨的曲子,可支持筛选的分轨 */
  411. canSelectTracks: [] as any,
  412. /** 声部codeId */
  413. subjectCodeId: 0 as number,
  414. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  415. musicalCodeId: 0 as number,
  416. /** 乐器code,用于评测传参 */
  417. musicalCode: '' as any,
  418. /** 合奏曲目是否合并展示 */
  419. isCombineRender: false,
  420. /** 小节的持续时长,以后台设置的播放速度计算 */
  421. measureTime: 0,
  422. /** 跟练模式,节拍器播放的时间 */
  423. beatStartTime: 0,
  424. /** 是否为详情预览模式 */
  425. isPreView: false,
  426. /** 是否为评测报告模式 */
  427. isEvaluatReport: false,
  428. /** midi播放器是否初始化中 */
  429. midiPlayIniting: false,
  430. /** 曲目信息 */
  431. songs: {} as ISonges,
  432. isAppPlay: false, // 是否midi音频,midi是app播放
  433. /** 音频播放器实例 */
  434. audiosInstance: null as any,
  435. /** midi音频的时长 */
  436. durationNum: 0,
  437. midiSectionStart: 0,
  438. /** 音频文件是否加载完成 */
  439. audioDone: false,
  440. /** 谱面svgdom节点 */
  441. osmdSvgDom: null as any,
  442. /** 滚动容器dom */
  443. osdmScrollDom: null as any,
  444. /** 光标dom */
  445. cursorDom: null as any,
  446. fistNoteLeft: 0,
  447. /** 是否为单行谱渲染模式 */
  448. isSingleLine: false,
  449. /** 首尾音符的间距 */
  450. noteDistance: 0,
  451. /** 一行谱运动模式,平滑移动、匀速移动 */
  452. moveType: "smooth" as "smooth" | "uniform",
  453. /** 是否是evxml */
  454. isEvxml: false,
  455. });
  456. const browserInfo = browser();
  457. let offset_duration = 0;
  458. /** 自定义数据 */
  459. export const customData = reactive({
  460. /** 自定义音符时值 */
  461. customNoteRealValue: [] as any,
  462. /** 自定义音符按读取到的时值 */
  463. customNoteCurrentTime: false,
  464. });
  465. /** 在渲染前后计算光标应该走到的音符 */
  466. const setStep = () => {
  467. // console.log('播放状态',state.playState)
  468. if (state.playState !== "play") {
  469. console.log("暂停播放");
  470. return;
  471. }
  472. let startTime = Date.now();
  473. requestAnimationFrame(() => {
  474. const endTime = Date.now();
  475. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  476. if (endTime - startTime < 16.7) {
  477. handlePlaying();
  478. setStep();
  479. } else {
  480. setTimeout(() => {
  481. handlePlaying();
  482. setStep();
  483. }, 16.7);
  484. }
  485. });
  486. };
  487. /** 开始播放 */
  488. export const onPlay = () => {
  489. console.log("开始播放");
  490. state.playEnd = false;
  491. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  492. offset_duration = 0.2;
  493. setStep();
  494. };
  495. /** 播放模式结束自动重播 */
  496. const autoResetPlay = () => {
  497. if (state.modeType !== "practise") return;
  498. skipNotePlay(0, true);
  499. // 没有开启自动重播, 不是练习模式
  500. if (!state.setting.repeatAutoPlay) return;
  501. scrollViewNote();
  502. setTimeout(() => {
  503. togglePlay("play");
  504. }, 1000);
  505. };
  506. /** 播放完成事件 */
  507. export const onEnded = () => {
  508. console.log("音频播放结束");
  509. // if (state.isAppPlay) {
  510. // // 销毁播放器
  511. // api_cloudDestroy();
  512. // }
  513. // 修改状态为结束
  514. state.playEnd = true;
  515. state.playState = "paused";
  516. // 结束播放
  517. audioListStart(state.playState);
  518. // 调用结束评测
  519. handleEndEvaluat(true);
  520. // 调用自动重复播放
  521. autoResetPlay();
  522. };
  523. /**
  524. * 播放一直触发的事件
  525. */
  526. const handlePlaying = () => {
  527. const currentTime = getAudioCurrentTime();
  528. const duration = getAudioDuration();
  529. state.playProgress = (currentTime / duration) * 100;
  530. let item = getNote(currentTime);
  531. // console.log(11111,currentTime,duration,state.playSource, item)
  532. // console.log(item.i,item.noteId,item.measureSpeed)
  533. // 练习模式下,实时刷新小节速度
  534. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  535. const ratio = state.speed / state.originSpeed
  536. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  537. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  538. state.playIngSpeed = state.speed
  539. }
  540. if (item) {
  541. // 选段状态下
  542. if (state.sectionStatus && state.section.length === 2) {
  543. // 如果开启了预备拍
  544. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  545. const selectEndItem = state.section[1];
  546. /**
  547. * #9374,反复小节的曲目播放错误, bug修复
  548. * 曲目:噢!苏珊娜-排箫-人音
  549. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  550. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  551. */
  552. if (state.repeatInfo.length) {
  553. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  554. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  555. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  556. const preItem = state.times[item.i - 1]
  557. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  558. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  559. if (skipItem) {
  560. // 跳转到指定的音频位置
  561. setAudioCurrentTime(skipItem.time, skipItem.i);
  562. gotoNext(skipItem);
  563. return
  564. }
  565. }
  566. }
  567. }
  568. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  569. // if (currentTime - selectEndItem.endtime > offset_duration) {
  570. //console.log(currentTime,selectEndItem.endtime)
  571. if (currentTime - selectEndItem.endtime >= 0) {
  572. console.log("选段播放结束",state.setting.repeatAutoPlay);
  573. // 如果为选段评测模式
  574. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  575. onEnded();
  576. return;
  577. }
  578. // #8698 bug修复
  579. if (state.modeType === "practise" && state.sectionStatus) {
  580. onEnded();
  581. resetPlaybackToStart();
  582. return;
  583. }
  584. item = selectStartItem;
  585. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  586. }
  587. }
  588. gotoNext(item);
  589. }
  590. // 评测不播放叮咚节拍器
  591. // if (state.modeType !== "evaluating") {
  592. // metronomeData.metro?.sound(currentTime);
  593. // }
  594. metronomeData.metro?.sound(currentTime);
  595. // 一行谱,需要滚动小节
  596. if (state.isSingleLine) {
  597. if (state.moveType === 'smooth') {
  598. smoothMoveSvgDom();
  599. } else {
  600. uniformMoveSvgDom();
  601. }
  602. }
  603. };
  604. /** 跳转到指定音符开始播放 */
  605. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  606. const item = state.times[itemIndex];
  607. let itemTime = item.time;
  608. if (isStart) {
  609. itemTime = 0;
  610. }
  611. if (item) {
  612. setAudioCurrentTime(itemTime, itemIndex);
  613. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  614. gotoNext(item, true);
  615. metronomeData.metro?.sound(itemTime);
  616. if (state.isAppPlay) {
  617. await api_cloudSetCurrentTime({
  618. currentTime: itemTime * 1000,
  619. songID: state.examSongId,
  620. })
  621. audioData.progress = itemTime
  622. state.midiSectionStart = itemTime
  623. }
  624. }
  625. };
  626. /**
  627. * 切换曲谱播放状态
  628. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  629. */
  630. export const togglePlay = async (playState?: "play" | "paused") => {
  631. // 如果mp3资源还在加载中,给出提示
  632. if (!state.isAppPlay && !state.audioDone) {
  633. showToast('音频资源加载中,请稍后')
  634. return
  635. }
  636. // midi播放
  637. if (state.isAppPlay) {
  638. if( playState === "paused" ) {
  639. await api_cloudSuspend({
  640. songID: state.examSongId,
  641. })
  642. state.playState = 'paused'
  643. return
  644. }
  645. skipNotePlay(state.activeNoteIndex, false);
  646. await api_cloudChangeSpeed({
  647. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  648. originalSpeed: state.originSpeed,
  649. songID: state.examSongId,
  650. });
  651. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  652. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  653. state.playState = status
  654. } else {
  655. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  656. }
  657. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  658. resetPlaybackToStart();
  659. }
  660. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  661. if (state.playState === "play" && state.needTick) {
  662. const tickend = await handleStartTick();
  663. // console.log("🚀 ~ tickend:", tickend)
  664. // 节拍器返回false, 取消播放
  665. if (!tickend) {
  666. state.playState = "paused";
  667. return false;
  668. }
  669. }
  670. // 如果选段没有结束, 直接开始播放,清空选段状态
  671. if (state.playState == "play") {
  672. if (state.sectionStatus && state.section.length < 2) {
  673. clearSelection();
  674. }
  675. }
  676. audioListStart(state.playState);
  677. return true;
  678. };
  679. /** 结束播放 */
  680. export const handleStopPlay = () => {
  681. state.playState = "paused";
  682. audioListStart(state.playState);
  683. };
  684. /** 重置播放为开始 */
  685. export const resetPlaybackToStart = () => {
  686. // 如果为选段状态
  687. if (state.sectionStatus && state.section.length === 2) {
  688. state.section = formateSelectMearure(state.section);
  689. return;
  690. } else {
  691. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  692. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  693. }
  694. skipNotePlay(0, true);
  695. };
  696. /** 跳转到指定音符 */
  697. export const gotoCustomNote = (index: number) => {
  698. try {
  699. state.osmd.cursor.reset();
  700. } catch (error) {}
  701. for (let i = 0; i < index; i++) {
  702. state.osmd.cursor.next();
  703. }
  704. };
  705. const setCursorPosition = (note: any, cursor: any) => {
  706. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  707. /**
  708. * bug:#9920、#9940
  709. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  710. */
  711. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  712. return
  713. }
  714. nextTick(() => {
  715. let bbox = note.bbox;
  716. if (!bbox) {
  717. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  718. x: 0,
  719. y: 0,
  720. };
  721. const parentLeft = musicContainer.x || 0;
  722. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  723. if (noteEle) {
  724. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  725. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  726. if (noteHeadBbox) {
  727. note.bbox = {
  728. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  729. width: noteHeadBbox.width * 1.5,
  730. };
  731. bbox = note.bbox;
  732. }
  733. }
  734. }
  735. if (!bbox) return;
  736. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  737. const width = (bbox.width - baseW) / 3;
  738. // console.log(555555,bbox.left,width)
  739. cursor.cursorElement.style.left = bbox.left + "px";
  740. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  741. });
  742. }
  743. };
  744. /**
  745. * 跳转到下一个音符
  746. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  747. **/
  748. export const gotoNext = (note: any, skipNote?: boolean) => {
  749. // console.log(33333333333,state.activeNoteIndex,note.i)
  750. const num = note.i;
  751. if (state.activeNoteIndex === note.i) {
  752. try {
  753. setCursorPosition(note, state.osmd.cursor);
  754. } catch (error) {
  755. console.log(error);
  756. }
  757. return;
  758. }
  759. const osmd = state.osmd;
  760. let prev = state.activeNoteIndex;
  761. state.activeNoteIndex = num;
  762. state.activeMeasureIndex = note.MeasureNumberXML;
  763. if (prev && num - prev === 1) {
  764. osmd.cursor.next();
  765. } else if (prev && num - prev > 0) {
  766. while (num - prev > 0) {
  767. prev++;
  768. osmd.cursor.next();
  769. }
  770. } else {
  771. gotoCustomNote(num);
  772. }
  773. try {
  774. setCursorPosition(note, state.osmd.cursor);
  775. } catch (error) {
  776. console.log(error);
  777. }
  778. // 一行谱,需要滚动小节
  779. if (state.isSingleLine) {
  780. moveSvgDom(skipNote);
  781. }
  782. scrollViewNote();
  783. };
  784. /** 获取指定音符 */
  785. export const getNote = (currentTime: number) => {
  786. const times = state.times;
  787. const len = state.times.length;
  788. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  789. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  790. onEnded();
  791. return;
  792. }
  793. let _item = null as any;
  794. for (let i = state.activeNoteIndex; i < len; i++) {
  795. const item = times[i];
  796. const prevItem = times[i - 1];
  797. if (currentTime >= item.time) {
  798. if (!prevItem || item.time != prevItem.time) {
  799. _item = item;
  800. }
  801. } else {
  802. break;
  803. }
  804. }
  805. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  806. return _item;
  807. };
  808. /** 重播 */
  809. export const handleResetPlay = () => {
  810. // 如果是midi需要重置播放进度
  811. if (state.isAppPlay) {
  812. audioData.progress = 0
  813. }
  814. resetPlaybackToStart();
  815. // 如果是暂停, 直接播放
  816. togglePlay("play");
  817. };
  818. /** 设置速度 */
  819. export const handleSetSpeed = (speed: number) => {
  820. setStorageSpeed(state.examSongId, speed);
  821. state.speed = speed;
  822. };
  823. /** 清除选段状态 */
  824. export const clearSelection = () => {
  825. state.sectionStatus = false;
  826. state.section = [];
  827. closeToast();
  828. };
  829. /** 开启选段 */
  830. export const handleChangeSection = () => {
  831. // 如果开启了选段,再次点击取消选段
  832. if (state.sectionStatus) {
  833. togglePlay("paused");
  834. clearSelection();
  835. skipNotePlay(0, true);
  836. state.sectionFirst = null;
  837. return;
  838. }
  839. state.sectionStatus = true;
  840. // 开启
  841. if (state.sectionStatus) {
  842. togglePlay("paused");
  843. }
  844. showToast({
  845. message: "请选择开始小节",
  846. duration: 0,
  847. position: "top",
  848. className: "selectionToast",
  849. });
  850. };
  851. /** 效验并格式化选段小节 */
  852. const formateSelectMearure = (_list: any[]): any[] => {
  853. if (!_list.length) return [];
  854. const list = _list.sort((a, b) => a.time - b.time);
  855. const startXml = list[0]?.measureOpenIndex;
  856. const endXml = list.last()?.measureOpenIndex;
  857. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  858. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  859. // 没有找到选段小节
  860. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  861. clearSelection();
  862. return [];
  863. }
  864. list[0] = selectStartMeasure[0];
  865. list[1] = selectEndMeasure.last();
  866. let startItemINdex = list[0].i;
  867. // 开启预备拍
  868. if (state.isOpenPrepare) {
  869. const startXmlIndex = list[0].MeasureNumberXML;
  870. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  871. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  872. }
  873. skipNotePlay(startItemINdex, startItemINdex === 0);
  874. return list;
  875. };
  876. /** 选择选段 */
  877. export const handleSelection = (item: any) => {
  878. if (!state.sectionStatus || state.section.length > 1) return;
  879. if (state.section.length !== 2 && item) {
  880. state.section.push(item);
  881. if (state.section.length === 2) {
  882. setSection(state.section[0].MeasureNumberXML,state.section[1].MeasureNumberXML)
  883. //state.section = formateSelectMearure(state.section);
  884. closeToast();
  885. }
  886. }
  887. if (state.section.length === 1) {
  888. showToast({
  889. message: "请选择结束小节",
  890. duration: 0,
  891. position: "top",
  892. className: "selectionToast",
  893. });
  894. }
  895. };
  896. /** 阶段练习、阶段评测设置选段小节 */
  897. export const setSection = (start: number, end: number, userSpeed?: number) => {
  898. const startNotes = state.times.filter(
  899. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  900. )
  901. const endNotes = state.times.filter(
  902. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  903. )
  904. state.userChooseEndIndex = end
  905. const lastEndId = endNotes[endNotes.length - 1].noteId
  906. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  907. // 是否符合重播规则
  908. const canRepeatInfo = verifyCanRepeat(start, end)
  909. console.log('能否重播',canRepeatInfo)
  910. const isCanRepeat = canRepeatInfo.canRepeat
  911. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  912. /**
  913. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  914. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  915. * TODO:通过vf-volta判断是否是跳房子
  916. */
  917. let isSkipVolta = false; // 结束小节是否是跳房子小节
  918. if (lastEndNotes.length === 1) {
  919. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  920. }
  921. let currentEndNum: number = end
  922. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  923. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  924. currentEndNum = currentEndNum - 1
  925. const newEndNotes = state.times.filter(
  926. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  927. )
  928. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  929. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  930. }
  931. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  932. const startNote = startNotes[0]
  933. // const endNote = endNotes[endNotes.length - 1]
  934. const endNote = lastEndNotes[endIdx]
  935. if (startNote && endNote) {
  936. state.isSelectMeasureMode = true;
  937. // 设置小节
  938. hanldeDirectSelection([startNote, endNote]);
  939. //设置速度
  940. if (userSpeed) {
  941. handleSetSpeed(userSpeed);
  942. }
  943. }
  944. }
  945. /** 直接设置选段 */
  946. export const hanldeDirectSelection = (list: any[]) => {
  947. if (!Array.isArray(list) || list.length !== 2) return;
  948. state.sectionStatus = true;
  949. setTimeout(() => {
  950. state.section = formateSelectMearure(list);
  951. console.log('选段小节',state.section)
  952. }, 500);
  953. };
  954. let offsetTop = 0;
  955. /**
  956. * 窗口内滚动到音符的区域
  957. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  958. * @returns void
  959. */
  960. export const scrollViewNote = () => {
  961. const cursorElement = document.getElementById("cursorImg-0")!;
  962. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  963. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  964. offsetTop = cursorElement.offsetTop;
  965. if (offsetTop > 50) {
  966. musicAndSelection.scrollTo({
  967. top: (offsetTop - 50) * state.musicZoom,
  968. behavior: "smooth",
  969. });
  970. } else {
  971. musicAndSelection.scrollTo({
  972. top: 0,
  973. behavior: "smooth",
  974. });
  975. }
  976. };
  977. /** 检测是否是节奏练习 */
  978. export const isRhythmicExercises = () => {
  979. return state.examSongName.indexOf("节奏练习") > -1;
  980. };
  981. /** 重置状态 */
  982. export const handleRessetState = () => {
  983. // 切换模式,清除选段
  984. clearSelection();
  985. skipNotePlay(0, true);
  986. // midi 重置播放进度
  987. if (state.isAppPlay) {
  988. audioData.progress = 0;
  989. }
  990. if (state.modeType === "evaluating") {
  991. handleStartEvaluat();
  992. } else if (state.modeType === "practise") {
  993. togglePlay("paused");
  994. } else if (state.modeType === "follow") {
  995. toggleFollow(false);
  996. }
  997. };
  998. export default state;
  999. /** 初始化评测音频 */
  1000. export const evaluatCreateMusicPlayer = () => {
  1001. return api_createMusicPlayer({
  1002. musicSrc: state.accompany || state.music, // 曲谱音频url
  1003. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1004. });
  1005. };
  1006. /** 获取内容平台的接口详情并初始化state信息 */
  1007. export const getMusicDetail = async (id: string) => {
  1008. const res = await getMusicSheetDetail(id);
  1009. if (res?.code === 200) {
  1010. getMusicInfo(res)
  1011. }
  1012. };
  1013. const getMusicInfo = (res: any) => {
  1014. const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
  1015. // 原音声轨
  1016. const musicData = res.data.musicSheetSoundList?.[index] || {};
  1017. // 伴奏声轨
  1018. const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
  1019. const musicInfo = {
  1020. ...res.data,
  1021. music: musicData.audioFileUrl || '',
  1022. accompany: accompanyData.audioFileUrl || '',
  1023. musicSheetId: musicData.musicSheetId || res.data.bizId,
  1024. track: musicData.track || '',
  1025. };
  1026. console.log("🚀 ~ musicInfo:", musicInfo);
  1027. setState(musicInfo, index);
  1028. };
  1029. const setState = (data: any, index: number) => {
  1030. state.appName = "COLEXIU";
  1031. state.detailId = data.bizId;
  1032. state.xmlUrl = data.xmlFileUrl;
  1033. state.partIndex = index;
  1034. state.trackId = data.track;
  1035. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1036. // 声部code
  1037. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1038. // 乐器code
  1039. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1040. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1041. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1042. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1043. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1044. state.categoriesId = data.musicCategoryId;
  1045. state.categoriesName = data.musicTagNames;
  1046. // state.enableEvaluation = data.isEvaluated ? true : false;
  1047. state.examSongId = data.bizId + "";
  1048. state.cbsExamSongId = data.id + "";
  1049. state.examSongName = data.name;
  1050. state.coverImg = data.musicCover ?? "";
  1051. // 单声部多声轨合并展示
  1052. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1053. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1054. // 解析扩展字段
  1055. if (data.extConfigJson) {
  1056. try {
  1057. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1058. } catch (error) {
  1059. console.error("解析扩展字段错误:", error);
  1060. }
  1061. }
  1062. state.gradualTimes = state.extConfigJson.gradualTimes;
  1063. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1064. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1065. // 曲子包含节拍器,就不开启节拍器
  1066. state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
  1067. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1068. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1069. state.isShowFingering = data.isShowFingering ? true : false;
  1070. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1071. state.isAppPlay = data.playMode === 'MIDI';
  1072. state.music = data.music;
  1073. state.accompany = data.accompany;
  1074. state.midiUrl = data.midiFileUrl;
  1075. state.parentCategoriesId = data.musicTag;
  1076. state.musicSheetCategoriesId = data.musicCategoryId;
  1077. state.bizMusicCategoryId = data.bizMusicCategoryId
  1078. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1079. state.originSpeed = state.speed = data.playSpeed;
  1080. // state.playIngSpeed = data.playSpeed;
  1081. const track = data.code || data.track;
  1082. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1083. // 能否评测,根据当前声轨有无伴奏判断
  1084. if (state.isAppPlay) {
  1085. state.enableEvaluation = state.midiUrl ? true : false
  1086. } else {
  1087. state.enableEvaluation = state.accompany ? true : false
  1088. }
  1089. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1090. // multiTracksSelection 返回为空,默认代表全部分轨
  1091. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1092. // 开启预备小节
  1093. state.isOpenPrepare = true;
  1094. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1095. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1096. // 是否打击乐
  1097. /**
  1098. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1099. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1100. * 打击乐&节奏练习,没有跟练模式
  1101. */
  1102. // state.isPercussion = isRhythmicExercises();
  1103. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1104. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1105. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1106. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1107. // 设置指法
  1108. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1109. /**
  1110. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1111. * 获取指法code
  1112. */
  1113. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1114. state.fingeringInfo = subjectFingering(code);
  1115. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1116. state.musicalCodeId = state.fingeringInfo?.id || 0
  1117. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1118. ;(window as any).DYSubjectId = state.musicalCodeId
  1119. // 开启自定义每行显示的小节数
  1120. ;(window as any).customSectionAmount = true
  1121. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1122. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1123. state.setting.displayFingering = false
  1124. }
  1125. // 检测是否原音和伴奏都有
  1126. if (!state.music || !state.accompany) {
  1127. state.playSource = state.music ? "music" : "background";
  1128. }
  1129. // 如果是PC端,放大曲谱
  1130. state.platform = query.platform?.toLocaleUpperCase() || "";
  1131. if (state.platform === IPlatform.PC) {
  1132. state.zoom = query.zoom || 1.5;
  1133. }
  1134. /**
  1135. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1136. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1137. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1138. *
  1139. */
  1140. let pitchTrack = null
  1141. if (state.isConcert) {
  1142. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1143. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1144. } else {
  1145. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1146. }
  1147. let musicalRenderType = ''
  1148. if (pitchTrack?.defaultScore) {
  1149. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1150. }
  1151. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1152. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1153. console.log("state对象", state);
  1154. // 评测基准频率
  1155. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1156. state.baseFrequency = Number(state.baseFrequency)
  1157. // 用户上次的频率和基准频率误差超过10,则重置
  1158. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1159. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1160. } else {
  1161. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1162. }
  1163. };
  1164. // 多分轨合并显示标示
  1165. const setCustom = (trackNum?: number) => {
  1166. if (trackNum || state.extConfigJson.multitrack) {
  1167. state.multitrack = trackNum || 0
  1168. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1169. }
  1170. };
  1171. /** 跟练模式播放节拍器(叮咚) */
  1172. export const followBeatPaly = () => {
  1173. let metroTimer: any = null;
  1174. if (!followData.start) {
  1175. clearTimeout(metroTimer)
  1176. metroTimer = null
  1177. return;
  1178. }
  1179. const time = state.measureTime*1000 / metronomeData.totalNumerator
  1180. requestAnimationFrame(() => {
  1181. const endTime = Date.now();
  1182. if (endTime - state.beatStartTime < time) {
  1183. followBeatPaly();
  1184. } else {
  1185. // metroTimer = setTimeout(() => {
  1186. // metronomeData.metro?.simulatePlayAudio()
  1187. // startTime = Date.now();
  1188. // followBeatPaly();
  1189. // }, time);
  1190. metronomeData.metro?.simulatePlayAudio()
  1191. state.beatStartTime = Date.now();
  1192. followBeatPaly();
  1193. }
  1194. });
  1195. };
  1196. // 音符添加bbox
  1197. export const addNoteBBox = (list: any[]) => {
  1198. let voicesBBox: any = null;
  1199. for (let i = 0; i < list.length; i++) {
  1200. const note = list[i];
  1201. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1202. /**
  1203. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1204. */
  1205. let bbox: any = null;
  1206. if (svgElement?.attrs.id) {
  1207. // @ts-ignore
  1208. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1209. bbox = {
  1210. x: bbox.x * state.zoom,
  1211. y: bbox.y * state.zoom,
  1212. width: bbox.width * state.zoom,
  1213. height: bbox.height * state.zoom,
  1214. }
  1215. } else {
  1216. // @ts-ignore
  1217. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1218. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1219. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1220. currentVoicesBBox = voicesBBox;
  1221. }
  1222. let nextIndex = i + 1;
  1223. while (!list[nextIndex].id && nextIndex < list.length) {
  1224. nextIndex += 1;
  1225. }
  1226. // 休止小节的开头和下一个音符之间的间距
  1227. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1228. if (list[nextIndex].id) {
  1229. // @ts-ignore
  1230. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1231. }
  1232. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1233. bbox = currentVoicesBBox ? {
  1234. bottom: currentVoicesBBox.bottom,
  1235. height: 30,
  1236. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1237. right: currentVoicesBBox.y,
  1238. top: currentVoicesBBox.top,
  1239. width: 1,
  1240. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1241. y: currentVoicesBBox.y,
  1242. svgBodyLeft: svgBodyBBox?.x,
  1243. } : null;
  1244. voicesBBox = currentVoicesBBox;
  1245. }
  1246. note.bbox = bbox;
  1247. }
  1248. }
  1249. // 一行谱模式,创建固定的光标
  1250. export const createFixedCursor = () => {
  1251. if (!state.isSingleLine) return;
  1252. const svg: any = document.getElementById("osmdSvgPage1");
  1253. state.osmdSvgDom = svg;
  1254. const scrollDom = document.getElementById("musicAndSelection");
  1255. const cursorDom = document.getElementById("cursorImg-0");
  1256. state.fistNoteLeft = cursorDom?.getBoundingClientRect()?.left || 0;
  1257. state.osdmScrollDom = scrollDom;
  1258. state.cursorDom = cursorDom;
  1259. let copyCursor: any = cursorDom?.cloneNode(true);
  1260. if (copyCursor) {
  1261. copyCursor.setAttribute('id','cursor-copy');
  1262. copyCursor.style.position = 'sticky';
  1263. copyCursor.style.zIndex = '2';
  1264. // if (!state.times[0]?.id) {
  1265. // copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 3 + 'px';
  1266. // }
  1267. copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 2 - 1 + 'px';
  1268. copyCursor.style.height = parseFloat(copyCursor.style.height) * 3 + 'px';
  1269. copyCursor.style.opacity = state.moveType === 'uniform' ? 0 : 1;
  1270. // copyCursor.style.background = 'red';
  1271. copyCursor && scrollDom?.appendChild(copyCursor);
  1272. // 创建左侧背景dom
  1273. // @ts-ignore
  1274. const firstMeasureBBox: any = document.querySelector('.vf-measure')?.getBBox();
  1275. const leftDom = document.createElement("div");
  1276. leftDom.style.width = state.times[0]?.bbox?.x - firstMeasureBBox?.x * state.zoom + 'px';
  1277. leftDom.style.height = firstMeasureBBox?.height * state.zoom + 'px';
  1278. leftDom.style.left = firstMeasureBBox?.x * state.zoom + 'px';
  1279. leftDom.style.transform = 'translateY(20px)';
  1280. leftDom.classList.add('leftNoteBg');
  1281. // scrollDom?.appendChild(leftDom);
  1282. }
  1283. }
  1284. /** 计算首尾音符的间距 */
  1285. export const calculateDistance = () => {
  1286. const firstNoteBBox = state.times[0]?.bbox;
  1287. const lastNoteBBox = state.times.last()?.bbox;
  1288. if (firstNoteBBox && lastNoteBBox) {
  1289. const noteDistance = lastNoteBBox.x - firstNoteBBox.x + lastNoteBBox.width / 2 - firstNoteBBox.width / 2 - 1;
  1290. console.log('首尾间距', noteDistance)
  1291. state.noteDistance = noteDistance || 0;
  1292. }
  1293. }
  1294. /** 跳动svgdom */
  1295. export const moveSvgDom = (skipNote?: boolean) => {
  1296. // const cursorLeft = state.cursorDom?.getBoundingClientRect()?.left || 0;
  1297. // const leftValue = parseFloat(state.cursorDom.style.left) - 47 - 20;
  1298. // console.log(cursorLeft,leftValue,'光标位置')
  1299. // state.osmdSvgDom.style.transform = `translateX(${-leftValue}px)`;
  1300. // state.osdmScrollDom.scrollLeft = leftValue
  1301. // console.log('当前音符',state.activeNoteIndex)
  1302. state.times.forEach((item: any, idx: number) => {
  1303. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1304. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1305. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1306. svgEl?.classList.add('noteActive')
  1307. stemEl?.classList.add('noteActive')
  1308. } else {
  1309. svgEl?.classList.remove('noteActive')
  1310. stemEl?.classList.remove('noteActive')
  1311. }
  1312. })
  1313. // document.getElementById('cursor-copy')?.classList.add('cursorAnimate');
  1314. /**
  1315. * 计算需要移动的距离
  1316. * 当前选中的音符和第一个音符之间的间距
  1317. */
  1318. if (skipNote) {
  1319. 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;
  1320. state.osdmScrollDom.scrollTo({
  1321. left: distance,
  1322. behavior: "smooth",
  1323. });
  1324. }
  1325. }
  1326. /** 平滑移动svgdom */
  1327. export const smoothMoveSvgDom = () => {
  1328. const currentTime = getAudioCurrentTime();
  1329. const matchNoteIdx = state.times.findIndex((item: any) => Math.abs(item.time - currentTime) * 1000 < 100 )
  1330. // if (matchNoteIdx >= 0) {
  1331. // console.log('匹配',matchNoteIdx,currentTime)
  1332. // }
  1333. if (currentTime <= state.fixtime) return;
  1334. if (currentTime > state.times.last()?.time) return;
  1335. // console.log('跳转音符',currentTime)
  1336. const currentBBox = state.times[state.activeNoteIndex]?.bbox;
  1337. let nextIndex = state.activeNoteIndex + 1;
  1338. let nextBBox = state.times[nextIndex]?.bbox;
  1339. while (!nextBBox && nextIndex < state.times.length) {
  1340. nextIndex += 1;
  1341. nextBBox = state.times[nextIndex]?.bbox;
  1342. }
  1343. // 下一个音符和当前播放音符之间的间距
  1344. let noteDistance = nextBBox?.x - state.times[state.activeNoteIndex].bbox?.x + nextBBox?.width / 4 - state.times[state.activeNoteIndex].bbox?.width / 4 || 0
  1345. if (noteDistance) {
  1346. // 当前的音符和下一个音符之间的时值
  1347. const noteDuration = state.times[nextIndex].time - state.times[state.activeNoteIndex]?.time;
  1348. // 当前时值在该区间的占比
  1349. const playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration;
  1350. // 如果当前播放的音符是休止小节的,实际没有音符
  1351. // if (!state.times[state.activeNoteIndex]?.id && state.times[state.activeNoteIndex]?.multipleRestMeasures && state.times[state.activeNoteIndex+1].id) {
  1352. // noteDistance = noteDistance - state.times[state.activeNoteIndex]?.bbox?.svgBodyLeft;
  1353. // }
  1354. const distance = noteDistance * playProgress;
  1355. // 上一个音符和第一个音符的间距
  1356. let preDistance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 4;
  1357. // console.log(state.activeNoteIndex,'滑动', distance, preDistance, state.osdmScrollDom.scrollLeft, noteDistance, nextIndex, currentTime, noteDuration )
  1358. // console.log('当前音符',state.activeNoteIndex,'距离',noteDistance,'比例',playProgress,'上一个距离',preDistance,'时值',currentTime, noteDuration)
  1359. //console.log('滑动','音符:',state.activeNoteIndex,'小节:', state.activeMeasureIndex)
  1360. state.osdmScrollDom.scrollLeft = distance + preDistance;
  1361. } else {
  1362. const playProgress = (currentTime - state.times[0]?.time) / state.times.last()?.time
  1363. const distance = state.noteDistance * playProgress;
  1364. state.osdmScrollDom.scrollLeft = distance;
  1365. }
  1366. }
  1367. // 匀速平移
  1368. export const uniformMoveSvgDom = () => {
  1369. const currentTime = getAudioCurrentTime();
  1370. if (currentTime <= state.fixtime) return;
  1371. if (currentTime > state.times.last()?.time) return;
  1372. const playProgress = (currentTime - state.fixtime) / state.times.last()?.time;
  1373. const distance = playProgress * state.noteDistance || 0;
  1374. state.osdmScrollDom.scrollLeft = distance;
  1375. }