state.ts 53 KB

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