state.ts 48 KB

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