state.ts 91 KB

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