state.ts 65 KB

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