state.ts 51 KB

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