state.ts 72 KB

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