state.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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节拍器的时间,统计拍数、速度计算得出 */
  371. fixtime: 0,
  372. /** 指法信息 */
  373. fingeringInfo: {} as IFingering,
  374. /** 滚动容器的ID */
  375. scrollContainer: "musicAndSelection",
  376. /** 是否是打击乐 */
  377. isPercussion: false,
  378. /** 评测标准 */
  379. evaluationStandard: '',
  380. /** 是否重复节拍器的时间 */
  381. repeatedBeats: 0,
  382. /**当前曲谱中所有声部名字 */
  383. partListNames: [] as any,
  384. /** 渐变速度信息 */
  385. gradual: [] as GradualNote[],
  386. /** 渐变速度版本 */
  387. gradualVersion: GradualVersion.BASE as GradualVersion,
  388. /** 渐变时间信息 */
  389. gradualTimes: null as GradualTimes,
  390. /** 单声部多声轨 */
  391. multitrack: 0,
  392. /** 缩放 */
  393. zoom: 0.8,
  394. /** 渲染曲谱比例 */
  395. musicZoom: 1,
  396. /** 练习,评测是否是选段模式 */
  397. isSelectMeasureMode: false,
  398. /** 是否是评分显示 */
  399. isReport: false,
  400. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  401. isHideEvaluatReportSaveBtn: false,
  402. /** 是否是合奏 */
  403. isConcert: false,
  404. /** 用户选择的结束小节数 */
  405. userChooseEndIndex: 0,
  406. /** 重播小节集合信息 */
  407. repeatInfo: [] as any,
  408. /** 多分轨的曲子,可支持筛选的分轨 */
  409. canSelectTracks: [] as any,
  410. /** 声部codeId */
  411. subjectCodeId: 0 as number,
  412. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  413. musicalCodeId: 0 as number,
  414. /** 乐器code,用于评测传参 */
  415. musicalCode: '' as any,
  416. /** 合奏曲目是否合并展示 */
  417. isCombineRender: false,
  418. /** 小节的持续时长,以后台设置的播放速度计算 */
  419. measureTime: 0,
  420. /** 跟练模式,节拍器播放的时间 */
  421. beatStartTime: 0,
  422. /** 是否为详情预览模式 */
  423. isPreView: false,
  424. /** 是否为评测报告模式 */
  425. isEvaluatReport: false,
  426. /** midi播放器是否初始化中 */
  427. midiPlayIniting: false,
  428. /** 曲目信息 */
  429. songs: {} as ISonges,
  430. isAppPlay: false, // 是否midi音频,midi是app播放
  431. /** 音频播放器实例 */
  432. audiosInstance: null as any,
  433. /** midi音频的时长 */
  434. durationNum: 0,
  435. midiSectionStart: 0,
  436. /** 音频文件是否加载完成 */
  437. audioDone: false,
  438. /** 谱面svgdom节点 */
  439. osmdSvgDom: null as any,
  440. /** 滚动容器dom */
  441. osdmScrollDom: null as any,
  442. /** 光标dom */
  443. cursorDom: null as any,
  444. fistNoteLeft: 0,
  445. /** 是否为单行谱渲染模式 */
  446. isSingleLine: false,
  447. /** 首尾音符的间距 */
  448. noteDistance: 0,
  449. });
  450. const browserInfo = browser();
  451. let offset_duration = 0;
  452. /** 自定义数据 */
  453. export const customData = reactive({
  454. /** 自定义音符时值 */
  455. customNoteRealValue: [] as any,
  456. /** 自定义音符按读取到的时值 */
  457. customNoteCurrentTime: false,
  458. });
  459. /** 在渲染前后计算光标应该走到的音符 */
  460. const setStep = () => {
  461. // console.log('播放状态',state.playState)
  462. if (state.playState !== "play") {
  463. console.log("暂停播放");
  464. return;
  465. }
  466. let startTime = Date.now();
  467. requestAnimationFrame(() => {
  468. const endTime = Date.now();
  469. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  470. if (endTime - startTime < 16.7) {
  471. handlePlaying();
  472. setStep();
  473. } else {
  474. setTimeout(() => {
  475. handlePlaying();
  476. setStep();
  477. }, 16.7);
  478. }
  479. });
  480. };
  481. /** 开始播放 */
  482. export const onPlay = () => {
  483. console.log("开始播放");
  484. state.playEnd = false;
  485. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  486. offset_duration = 0.2;
  487. setStep();
  488. };
  489. /** 播放模式结束自动重播 */
  490. const autoResetPlay = () => {
  491. if (state.modeType !== "practise") return;
  492. skipNotePlay(0, true);
  493. // 没有开启自动重播, 不是练习模式
  494. if (!state.setting.repeatAutoPlay) return;
  495. scrollViewNote();
  496. setTimeout(() => {
  497. togglePlay("play");
  498. }, 1000);
  499. };
  500. /** 播放完成事件 */
  501. export const onEnded = () => {
  502. console.log("音频播放结束");
  503. // if (state.isAppPlay) {
  504. // // 销毁播放器
  505. // api_cloudDestroy();
  506. // }
  507. // 修改状态为结束
  508. state.playEnd = true;
  509. state.playState = "paused";
  510. // 结束播放
  511. audioListStart(state.playState);
  512. // 调用结束评测
  513. handleEndEvaluat(true);
  514. // 调用自动重复播放
  515. autoResetPlay();
  516. };
  517. /**
  518. * 播放一直触发的事件
  519. */
  520. const handlePlaying = () => {
  521. const currentTime = getAudioCurrentTime();
  522. const duration = getAudioDuration();
  523. state.playProgress = (currentTime / duration) * 100;
  524. let item = getNote(currentTime);
  525. // console.log(11111,currentTime,duration,state.playSource, item)
  526. // console.log(item.i,item.noteId,item.measureSpeed)
  527. // 练习模式下,实时刷新小节速度
  528. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  529. const ratio = state.speed / state.originSpeed
  530. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  531. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  532. state.playIngSpeed = state.speed
  533. }
  534. if (item) {
  535. // 选段状态下
  536. if (state.sectionStatus && state.section.length === 2) {
  537. // 如果开启了预备拍
  538. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  539. const selectEndItem = state.section[1];
  540. /**
  541. * #9374,反复小节的曲目播放错误, bug修复
  542. * 曲目:噢!苏珊娜-排箫-人音
  543. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  544. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  545. */
  546. if (state.repeatInfo.length) {
  547. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  548. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  549. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  550. const preItem = state.times[item.i - 1]
  551. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  552. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  553. if (skipItem) {
  554. // 跳转到指定的音频位置
  555. setAudioCurrentTime(skipItem.time, skipItem.i);
  556. gotoNext(skipItem);
  557. return
  558. }
  559. }
  560. }
  561. }
  562. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  563. // if (currentTime - selectEndItem.endtime > offset_duration) {
  564. //console.log(currentTime,selectEndItem.endtime)
  565. if (currentTime - selectEndItem.endtime >= 0) {
  566. console.log("选段播放结束",state.setting.repeatAutoPlay);
  567. // 如果为选段评测模式
  568. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  569. onEnded();
  570. return;
  571. }
  572. // #8698 bug修复
  573. if (state.modeType === "practise" && state.sectionStatus) {
  574. onEnded();
  575. resetPlaybackToStart();
  576. return;
  577. }
  578. item = selectStartItem;
  579. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  580. }
  581. }
  582. gotoNext(item);
  583. }
  584. // 评测不播放叮咚节拍器
  585. // if (state.modeType !== "evaluating") {
  586. // metronomeData.metro?.sound(currentTime);
  587. // }
  588. metronomeData.metro?.sound(currentTime);
  589. // 一行谱,需要滚动小节
  590. if (state.isSingleLine) {
  591. smoothMoveSvgDom();
  592. }
  593. };
  594. /** 跳转到指定音符开始播放 */
  595. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  596. const item = state.times[itemIndex];
  597. let itemTime = item.time;
  598. if (isStart) {
  599. itemTime = 0;
  600. }
  601. if (item) {
  602. setAudioCurrentTime(itemTime, itemIndex);
  603. gotoNext(item);
  604. metronomeData.metro?.sound(itemTime);
  605. if (state.isAppPlay) {
  606. await api_cloudSetCurrentTime({
  607. currentTime: itemTime * 1000,
  608. songID: state.examSongId,
  609. })
  610. audioData.progress = itemTime
  611. state.midiSectionStart = itemTime
  612. }
  613. }
  614. };
  615. /**
  616. * 切换曲谱播放状态
  617. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  618. */
  619. export const togglePlay = async (playState?: "play" | "paused") => {
  620. // 如果mp3资源还在加载中,给出提示
  621. if (!state.isAppPlay && !state.audioDone) {
  622. showToast('音频资源加载中,请稍后')
  623. return
  624. }
  625. // midi播放
  626. if (state.isAppPlay) {
  627. if( playState === "paused" ) {
  628. await api_cloudSuspend({
  629. songID: state.examSongId,
  630. })
  631. state.playState = 'paused'
  632. return
  633. }
  634. skipNotePlay(state.activeNoteIndex, false);
  635. await api_cloudChangeSpeed({
  636. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  637. originalSpeed: state.originSpeed,
  638. songID: state.examSongId,
  639. });
  640. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  641. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  642. state.playState = status
  643. } else {
  644. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  645. }
  646. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  647. resetPlaybackToStart();
  648. }
  649. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  650. if (state.playState === "play" && state.needTick) {
  651. const tickend = await handleStartTick();
  652. // console.log("🚀 ~ tickend:", tickend)
  653. // 节拍器返回false, 取消播放
  654. if (!tickend) {
  655. state.playState = "paused";
  656. return false;
  657. }
  658. }
  659. // 如果选段没有结束, 直接开始播放,清空选段状态
  660. if (state.playState == "play") {
  661. if (state.sectionStatus && state.section.length < 2) {
  662. clearSelection();
  663. }
  664. }
  665. audioListStart(state.playState);
  666. return true;
  667. };
  668. /** 结束播放 */
  669. export const handleStopPlay = () => {
  670. state.playState = "paused";
  671. audioListStart(state.playState);
  672. };
  673. /** 重置播放为开始 */
  674. export const resetPlaybackToStart = () => {
  675. // 如果为选段状态
  676. if (state.sectionStatus && state.section.length === 2) {
  677. state.section = formateSelectMearure(state.section);
  678. return;
  679. } else {
  680. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  681. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  682. }
  683. skipNotePlay(0, true);
  684. };
  685. /** 跳转到指定音符 */
  686. export const gotoCustomNote = (index: number) => {
  687. try {
  688. state.osmd.cursor.reset();
  689. } catch (error) {}
  690. for (let i = 0; i < index; i++) {
  691. state.osmd.cursor.next();
  692. }
  693. };
  694. const setCursorPosition = (note: any, cursor: any) => {
  695. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  696. /**
  697. * bug:#9920、#9940
  698. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  699. */
  700. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  701. return
  702. }
  703. nextTick(() => {
  704. let bbox = note.bbox;
  705. if (!bbox) {
  706. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  707. x: 0,
  708. y: 0,
  709. };
  710. const parentLeft = musicContainer.x || 0;
  711. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  712. if (noteEle) {
  713. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  714. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  715. if (noteHeadBbox) {
  716. note.bbox = {
  717. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  718. width: noteHeadBbox.width * 1.5,
  719. };
  720. bbox = note.bbox;
  721. }
  722. }
  723. }
  724. if (!bbox) return;
  725. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  726. const width = (bbox.width - baseW) / 3;
  727. // console.log(555555,bbox.left,width)
  728. cursor.cursorElement.style.left = bbox.left + "px";
  729. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  730. });
  731. }
  732. };
  733. /** 跳转到下一个音符 */
  734. export const gotoNext = (note: any) => {
  735. // console.log(33333333333,state.activeNoteIndex,note.i)
  736. const num = note.i;
  737. if (state.activeNoteIndex === note.i) {
  738. try {
  739. setCursorPosition(note, state.osmd.cursor);
  740. } catch (error) {
  741. console.log(error);
  742. }
  743. return;
  744. }
  745. const osmd = state.osmd;
  746. let prev = state.activeNoteIndex;
  747. state.activeNoteIndex = num;
  748. state.activeMeasureIndex = note.MeasureNumberXML;
  749. if (prev && num - prev === 1) {
  750. osmd.cursor.next();
  751. } else if (prev && num - prev > 0) {
  752. while (num - prev > 0) {
  753. prev++;
  754. osmd.cursor.next();
  755. }
  756. } else {
  757. gotoCustomNote(num);
  758. }
  759. try {
  760. setCursorPosition(note, state.osmd.cursor);
  761. } catch (error) {
  762. console.log(error);
  763. }
  764. // 一行谱,需要滚动小节
  765. if (state.isSingleLine) {
  766. moveSvgDom();
  767. }
  768. scrollViewNote();
  769. };
  770. /** 获取指定音符 */
  771. export const getNote = (currentTime: number) => {
  772. const times = state.times;
  773. const len = state.times.length;
  774. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  775. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  776. onEnded();
  777. return;
  778. }
  779. let _item = null as any;
  780. for (let i = state.activeNoteIndex; i < len; i++) {
  781. const item = times[i];
  782. const prevItem = times[i - 1];
  783. if (currentTime >= item.time) {
  784. if (!prevItem || item.time != prevItem.time) {
  785. _item = item;
  786. }
  787. } else {
  788. break;
  789. }
  790. }
  791. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  792. return _item;
  793. };
  794. /** 重播 */
  795. export const handleResetPlay = () => {
  796. // 如果是midi需要重置播放进度
  797. if (state.isAppPlay) {
  798. audioData.progress = 0
  799. }
  800. resetPlaybackToStart();
  801. // 如果是暂停, 直接播放
  802. togglePlay("play");
  803. };
  804. /** 设置速度 */
  805. export const handleSetSpeed = (speed: number) => {
  806. setStorageSpeed(state.examSongId, speed);
  807. state.speed = speed;
  808. };
  809. /** 清除选段状态 */
  810. export const clearSelection = () => {
  811. state.sectionStatus = false;
  812. state.section = [];
  813. closeToast();
  814. };
  815. /** 开启选段 */
  816. export const handleChangeSection = () => {
  817. // 如果开启了选段,再次点击取消选段
  818. if (state.sectionStatus) {
  819. togglePlay("paused");
  820. clearSelection();
  821. skipNotePlay(0, true);
  822. state.sectionFirst = null;
  823. return;
  824. }
  825. state.sectionStatus = true;
  826. // 开启
  827. if (state.sectionStatus) {
  828. togglePlay("paused");
  829. }
  830. showToast({
  831. message: "请选择开始小节",
  832. duration: 0,
  833. position: "top",
  834. className: "selectionToast",
  835. });
  836. };
  837. /** 效验并格式化选段小节 */
  838. const formateSelectMearure = (_list: any[]): any[] => {
  839. if (!_list.length) return [];
  840. const list = _list.sort((a, b) => a.time - b.time);
  841. const startXml = list[0]?.measureOpenIndex;
  842. const endXml = list.last()?.measureOpenIndex;
  843. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  844. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  845. // 没有找到选段小节
  846. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  847. clearSelection();
  848. return [];
  849. }
  850. list[0] = selectStartMeasure[0];
  851. list[1] = selectEndMeasure.last();
  852. let startItemINdex = list[0].i;
  853. // 开启预备拍
  854. if (state.isOpenPrepare) {
  855. const startXmlIndex = list[0].MeasureNumberXML;
  856. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  857. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  858. }
  859. skipNotePlay(startItemINdex, startItemINdex === 0);
  860. return list;
  861. };
  862. /** 选择选段 */
  863. export const handleSelection = (item: any) => {
  864. if (!state.sectionStatus || state.section.length > 1) return;
  865. if (state.section.length !== 2 && item) {
  866. state.section.push(item);
  867. if (state.section.length === 2) {
  868. setSection(state.section[0].MeasureNumberXML,state.section[1].MeasureNumberXML)
  869. //state.section = formateSelectMearure(state.section);
  870. closeToast();
  871. }
  872. }
  873. if (state.section.length === 1) {
  874. showToast({
  875. message: "请选择结束小节",
  876. duration: 0,
  877. position: "top",
  878. className: "selectionToast",
  879. });
  880. }
  881. };
  882. /** 阶段练习、阶段评测设置选段小节 */
  883. export const setSection = (start: number, end: number, userSpeed?: number) => {
  884. const startNotes = state.times.filter(
  885. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  886. )
  887. const endNotes = state.times.filter(
  888. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  889. )
  890. state.userChooseEndIndex = end
  891. const lastEndId = endNotes[endNotes.length - 1].noteId
  892. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  893. // 是否符合重播规则
  894. const canRepeatInfo = verifyCanRepeat(start, end)
  895. console.log('能否重播',canRepeatInfo)
  896. const isCanRepeat = canRepeatInfo.canRepeat
  897. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  898. /**
  899. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  900. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  901. * TODO:通过vf-volta判断是否是跳房子
  902. */
  903. let isSkipVolta = false; // 结束小节是否是跳房子小节
  904. if (lastEndNotes.length === 1) {
  905. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  906. }
  907. let currentEndNum: number = end
  908. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  909. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  910. currentEndNum = currentEndNum - 1
  911. const newEndNotes = state.times.filter(
  912. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  913. )
  914. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  915. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  916. }
  917. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  918. const startNote = startNotes[0]
  919. // const endNote = endNotes[endNotes.length - 1]
  920. const endNote = lastEndNotes[endIdx]
  921. if (startNote && endNote) {
  922. state.isSelectMeasureMode = true;
  923. // 设置小节
  924. hanldeDirectSelection([startNote, endNote]);
  925. //设置速度
  926. if (userSpeed) {
  927. handleSetSpeed(userSpeed);
  928. }
  929. }
  930. }
  931. /** 直接设置选段 */
  932. export const hanldeDirectSelection = (list: any[]) => {
  933. if (!Array.isArray(list) || list.length !== 2) return;
  934. state.sectionStatus = true;
  935. setTimeout(() => {
  936. state.section = formateSelectMearure(list);
  937. console.log('选段小节',state.section)
  938. }, 500);
  939. };
  940. let offsetTop = 0;
  941. /**
  942. * 窗口内滚动到音符的区域
  943. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  944. * @returns void
  945. */
  946. export const scrollViewNote = () => {
  947. const cursorElement = document.getElementById("cursorImg-0")!;
  948. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  949. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  950. offsetTop = cursorElement.offsetTop;
  951. if (offsetTop > 50) {
  952. musicAndSelection.scrollTo({
  953. top: (offsetTop - 50) * state.musicZoom,
  954. behavior: "smooth",
  955. });
  956. } else {
  957. musicAndSelection.scrollTo({
  958. top: 0,
  959. behavior: "smooth",
  960. });
  961. }
  962. };
  963. /** 检测是否是节奏练习 */
  964. export const isRhythmicExercises = () => {
  965. return state.examSongName.indexOf("节奏练习") > -1;
  966. };
  967. /** 重置状态 */
  968. export const handleRessetState = () => {
  969. // 切换模式,清除选段
  970. clearSelection();
  971. skipNotePlay(0, true);
  972. // midi 重置播放进度
  973. if (state.isAppPlay) {
  974. audioData.progress = 0;
  975. }
  976. if (state.modeType === "evaluating") {
  977. handleStartEvaluat();
  978. } else if (state.modeType === "practise") {
  979. togglePlay("paused");
  980. } else if (state.modeType === "follow") {
  981. toggleFollow(false);
  982. }
  983. };
  984. export default state;
  985. /** 初始化评测音频 */
  986. export const evaluatCreateMusicPlayer = () => {
  987. return api_createMusicPlayer({
  988. musicSrc: state.accompany || state.music, // 曲谱音频url
  989. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  990. });
  991. };
  992. /** 获取内容平台的接口详情并初始化state信息 */
  993. export const getMusicDetail = async (id: string) => {
  994. const res = await getMusicSheetDetail(id);
  995. if (res?.code === 200) {
  996. getMusicInfo(res)
  997. }
  998. };
  999. const getMusicInfo = (res: any) => {
  1000. const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
  1001. // 原音声轨
  1002. const musicData = res.data.musicSheetSoundList?.[index] || {};
  1003. // 伴奏声轨
  1004. const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
  1005. const musicInfo = {
  1006. ...res.data,
  1007. music: musicData.audioFileUrl || '',
  1008. accompany: accompanyData.audioFileUrl || '',
  1009. musicSheetId: musicData.musicSheetId || res.data.bizId,
  1010. track: musicData.track || '',
  1011. };
  1012. console.log("🚀 ~ musicInfo:", musicInfo);
  1013. setState(musicInfo, index);
  1014. };
  1015. const setState = (data: any, index: number) => {
  1016. state.appName = "COLEXIU";
  1017. state.detailId = data.bizId;
  1018. state.xmlUrl = data.xmlFileUrl;
  1019. state.partIndex = index;
  1020. state.trackId = data.track;
  1021. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1022. // 声部code
  1023. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1024. // 乐器code
  1025. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1026. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1027. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1028. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1029. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1030. state.categoriesId = data.musicCategoryId;
  1031. state.categoriesName = data.musicTagNames;
  1032. // state.enableEvaluation = data.isEvaluated ? true : false;
  1033. state.examSongId = data.bizId + "";
  1034. state.cbsExamSongId = data.id + "";
  1035. state.examSongName = data.name;
  1036. state.coverImg = data.musicCover ?? "";
  1037. // 单声部多声轨合并展示
  1038. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1039. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1040. // 解析扩展字段
  1041. if (data.extConfigJson) {
  1042. try {
  1043. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1044. } catch (error) {
  1045. console.error("解析扩展字段错误:", error);
  1046. }
  1047. }
  1048. state.gradualTimes = state.extConfigJson.gradualTimes;
  1049. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1050. // 曲子包含节拍器,就不开启节拍器
  1051. state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
  1052. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1053. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1054. state.isShowFingering = data.isShowFingering ? true : false;
  1055. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1056. state.isAppPlay = data.playMode === 'MIDI';
  1057. state.music = data.music;
  1058. state.accompany = data.accompany;
  1059. state.midiUrl = data.midiFileUrl;
  1060. state.parentCategoriesId = data.musicTag;
  1061. state.musicSheetCategoriesId = data.musicCategoryId;
  1062. state.bizMusicCategoryId = data.bizMusicCategoryId
  1063. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1064. state.originSpeed = state.speed = data.playSpeed;
  1065. // state.playIngSpeed = data.playSpeed;
  1066. const track = data.code || data.track;
  1067. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1068. // 能否评测,根据当前声轨有无伴奏判断
  1069. if (state.isAppPlay) {
  1070. state.enableEvaluation = state.midiUrl ? true : false
  1071. } else {
  1072. state.enableEvaluation = state.accompany ? true : false
  1073. }
  1074. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1075. // multiTracksSelection 返回为空,默认代表全部分轨
  1076. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1077. // 开启预备小节
  1078. state.isOpenPrepare = true;
  1079. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1080. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1081. // 是否打击乐
  1082. /**
  1083. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1084. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1085. * 打击乐&节奏练习,没有跟练模式
  1086. */
  1087. // state.isPercussion = isRhythmicExercises();
  1088. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1089. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1090. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1091. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1092. // 设置指法
  1093. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1094. /**
  1095. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1096. * 获取指法code
  1097. */
  1098. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1099. state.fingeringInfo = subjectFingering(code);
  1100. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1101. state.musicalCodeId = state.fingeringInfo?.id || 0
  1102. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1103. ;(window as any).DYSubjectId = state.musicalCodeId
  1104. // 开启自定义每行显示的小节数
  1105. ;(window as any).customSectionAmount = true
  1106. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1107. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1108. state.setting.displayFingering = false
  1109. }
  1110. // 检测是否原音和伴奏都有
  1111. if (!state.music || !state.accompany) {
  1112. state.playSource = state.music ? "music" : "background";
  1113. }
  1114. // 如果是PC端,放大曲谱
  1115. state.platform = query.platform?.toLocaleUpperCase() || "";
  1116. if (state.platform === IPlatform.PC) {
  1117. state.zoom = query.zoom || 1.5;
  1118. }
  1119. /**
  1120. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1121. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1122. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1123. *
  1124. */
  1125. let pitchTrack = null
  1126. if (state.isConcert) {
  1127. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1128. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1129. } else {
  1130. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1131. }
  1132. let musicalRenderType = ''
  1133. if (pitchTrack?.defaultScore) {
  1134. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1135. }
  1136. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1137. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1138. console.log("state对象", state);
  1139. // 评测基准频率
  1140. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1141. state.baseFrequency = Number(state.baseFrequency)
  1142. // 用户上次的频率和基准频率误差超过10,则重置
  1143. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1144. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1145. } else {
  1146. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1147. }
  1148. };
  1149. // 多分轨合并显示标示
  1150. const setCustom = (trackNum?: number) => {
  1151. if (trackNum || state.extConfigJson.multitrack) {
  1152. state.multitrack = trackNum || 0
  1153. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1154. }
  1155. };
  1156. /** 跟练模式播放节拍器(叮咚) */
  1157. export const followBeatPaly = () => {
  1158. let metroTimer: any = null;
  1159. if (!followData.start) {
  1160. clearTimeout(metroTimer)
  1161. metroTimer = null
  1162. return;
  1163. }
  1164. const time = state.measureTime*1000 / metronomeData.totalNumerator
  1165. requestAnimationFrame(() => {
  1166. const endTime = Date.now();
  1167. if (endTime - state.beatStartTime < time) {
  1168. followBeatPaly();
  1169. } else {
  1170. // metroTimer = setTimeout(() => {
  1171. // metronomeData.metro?.simulatePlayAudio()
  1172. // startTime = Date.now();
  1173. // followBeatPaly();
  1174. // }, time);
  1175. metronomeData.metro?.simulatePlayAudio()
  1176. state.beatStartTime = Date.now();
  1177. followBeatPaly();
  1178. }
  1179. });
  1180. };
  1181. // 音符添加bbox
  1182. export const addNoteBBox = (list: any[]) => {
  1183. let voicesBBox: any = null;
  1184. for (let i = 0; i < list.length; i++) {
  1185. const note = list[i];
  1186. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1187. /**
  1188. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1189. */
  1190. let bbox: any = null;
  1191. if (svgElement?.attrs.id) {
  1192. // @ts-ignore
  1193. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1194. bbox = {
  1195. x: bbox.x * state.zoom,
  1196. y: bbox.y * state.zoom,
  1197. width: bbox.width * state.zoom,
  1198. height: bbox.height * state.zoom,
  1199. }
  1200. } else {
  1201. // @ts-ignore
  1202. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1203. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1204. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1205. currentVoicesBBox = voicesBBox;
  1206. }
  1207. let nextIndex = i + 1;
  1208. while (!list[nextIndex].id && nextIndex < list.length) {
  1209. nextIndex += 1;
  1210. }
  1211. // 休止小节的开头和下一个音符之间的间距
  1212. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1213. if (list[nextIndex].id) {
  1214. // @ts-ignore
  1215. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1216. }
  1217. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1218. bbox = currentVoicesBBox ? {
  1219. bottom: currentVoicesBBox.bottom,
  1220. height: 30,
  1221. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1222. right: currentVoicesBBox.y,
  1223. top: currentVoicesBBox.top,
  1224. width: 1,
  1225. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1226. y: currentVoicesBBox.y,
  1227. svgBodyLeft: svgBodyBBox?.x,
  1228. } : null;
  1229. voicesBBox = currentVoicesBBox;
  1230. }
  1231. note.bbox = bbox;
  1232. }
  1233. }
  1234. // 一行谱模式,创建固定的光标
  1235. export const createFixedCursor = () => {
  1236. if (!state.isSingleLine) return;
  1237. const svg: any = document.getElementById("osmdSvgPage1");
  1238. state.osmdSvgDom = svg;
  1239. const scrollDom = document.getElementById("musicAndSelection");
  1240. const cursorDom = document.getElementById("cursorImg-0");
  1241. state.fistNoteLeft = cursorDom?.getBoundingClientRect()?.left || 0;
  1242. state.osdmScrollDom = scrollDom;
  1243. state.cursorDom = cursorDom;
  1244. let copyCursor: any = cursorDom?.cloneNode(true);
  1245. if (copyCursor) {
  1246. copyCursor.setAttribute('id','cursor-copy');
  1247. copyCursor.style.position = 'sticky';
  1248. copyCursor.style.zIndex = '2';
  1249. // if (!state.times[0]?.id) {
  1250. // copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 3 + 'px';
  1251. // }
  1252. copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 2 - 1 + 'px';
  1253. copyCursor.style.height = parseFloat(copyCursor.style.height) * 3 + 'px';
  1254. // copyCursor.style.background = 'red';
  1255. copyCursor && scrollDom?.appendChild(copyCursor);
  1256. // 创建左侧背景dom
  1257. // @ts-ignore
  1258. const firstMeasureBBox: any = document.querySelector('.vf-measure')?.getBBox();
  1259. const leftDom = document.createElement("div");
  1260. leftDom.style.width = state.times[0]?.bbox?.x - firstMeasureBBox?.x * state.zoom + 'px';
  1261. leftDom.style.height = firstMeasureBBox?.height * state.zoom + 'px';
  1262. leftDom.style.left = firstMeasureBBox?.x * state.zoom + 'px';
  1263. leftDom.style.top = '20px';
  1264. leftDom.classList.add('leftNoteBg');
  1265. scrollDom?.appendChild(leftDom);
  1266. }
  1267. }
  1268. /** 计算首尾音符的间距 */
  1269. export const calculateDistance = () => {
  1270. const firstNoteRect = document.getElementById(`vf-${state.times[0]?.svgElement?.attrs?.id}`)?.getBoundingClientRect();
  1271. const lastNoteRect = document.getElementById(`vf-${state.times.last()?.svgElement?.attrs?.id}`)?.getBoundingClientRect();
  1272. if (firstNoteRect && lastNoteRect) {
  1273. const noteDistance = lastNoteRect.x - firstNoteRect.x + lastNoteRect.width / 3;
  1274. console.log('首尾间距', noteDistance)
  1275. state.noteDistance = noteDistance || 0;
  1276. }
  1277. }
  1278. /** 跳动svgdom */
  1279. export const moveSvgDom = () => {
  1280. // const cursorLeft = state.cursorDom?.getBoundingClientRect()?.left || 0;
  1281. // const leftValue = parseFloat(state.cursorDom.style.left) - 47 - 20;
  1282. // console.log(cursorLeft,leftValue,'光标位置')
  1283. // state.osmdSvgDom.style.transform = `translateX(${-leftValue}px)`;
  1284. // state.osdmScrollDom.scrollLeft = leftValue
  1285. // console.log('当前音符',state.activeNoteIndex)
  1286. state.times.forEach((item: any, idx: number) => {
  1287. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1288. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1289. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1290. svgEl?.classList.add('noteActive')
  1291. stemEl?.classList.add('noteActive')
  1292. } else {
  1293. svgEl?.classList.remove('noteActive')
  1294. stemEl?.classList.remove('noteActive')
  1295. }
  1296. })
  1297. // document.getElementById('cursor-copy')?.classList.add('cursorAnimate');
  1298. /**
  1299. * 计算需要移动的距离
  1300. * 当前选中的音符和第一个音符之间的间距
  1301. */
  1302. 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;
  1303. state.osdmScrollDom.scrollTo({
  1304. left: distance,
  1305. behavior: "smooth",
  1306. });
  1307. }
  1308. /** 平滑移动svgdom */
  1309. export const smoothMoveSvgDom = () => {
  1310. const currentTime = getAudioCurrentTime();
  1311. const matchNoteIdx = state.times.findIndex((item: any) => Math.abs(item.time - currentTime) * 1000 < 100 )
  1312. // if (matchNoteIdx >= 0) {
  1313. // console.log('匹配',matchNoteIdx,currentTime)
  1314. // }
  1315. if (currentTime <= state.fixtime) return;
  1316. if (currentTime > state.times.last()?.time) return;
  1317. // console.log('跳转音符',currentTime)
  1318. const currentBBox = state.times[state.activeNoteIndex]?.bbox;
  1319. let nextIndex = state.activeNoteIndex + 1;
  1320. let nextBBox = state.times[nextIndex]?.bbox;
  1321. while (!nextBBox && nextIndex < state.times.length) {
  1322. nextIndex += 1;
  1323. nextBBox = state.times[nextIndex]?.bbox;
  1324. }
  1325. // 下一个音符和当前播放音符之间的间距
  1326. let noteDistance = nextBBox?.x - state.times[state.activeNoteIndex].bbox?.x + nextBBox?.width / 4 - state.times[state.activeNoteIndex].bbox?.width / 4 || 0
  1327. if (noteDistance) {
  1328. // 当前的音符和下一个音符之间的时值
  1329. const noteDuration = state.times[nextIndex].time - state.times[state.activeNoteIndex]?.time;
  1330. // 当前时值在该区间的占比
  1331. const playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration;
  1332. // 如果当前播放的音符是休止小节的,实际没有音符
  1333. // if (!state.times[state.activeNoteIndex]?.id && state.times[state.activeNoteIndex]?.multipleRestMeasures && state.times[state.activeNoteIndex+1].id) {
  1334. // noteDistance = noteDistance - state.times[state.activeNoteIndex]?.bbox?.svgBodyLeft;
  1335. // }
  1336. const distance = noteDistance * playProgress;
  1337. // 上一个音符和第一个音符的间距
  1338. let preDistance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 4;
  1339. // console.log(state.activeNoteIndex,'滑动', distance, preDistance, state.osdmScrollDom.scrollLeft, noteDistance, nextIndex, currentTime, noteDuration )
  1340. // console.log('当前音符',state.activeNoteIndex,'距离',noteDistance,'比例',playProgress,'上一个距离',preDistance,'时值',currentTime, noteDuration)
  1341. //console.log('滑动','音符:',state.activeNoteIndex,'小节:', state.activeMeasureIndex)
  1342. state.osdmScrollDom.scrollLeft = distance + preDistance;
  1343. } else {
  1344. const playProgress = (currentTime - state.times[0]?.time) / state.times.last()?.time
  1345. const distance = state.noteDistance * playProgress;
  1346. state.osdmScrollDom.scrollLeft = distance;
  1347. }
  1348. }