state.ts 88 KB

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