1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441 |
- import { closeToast, showToast } from "vant";
- import { nextTick, reactive } from "vue";
- import { OpenSheetMusicDisplay } from "../osmd-extended/src";
- import { metronomeData } from "./helpers/metronome";
- import { GradualNote, GradualTimes, GradualVersion } from "./type";
- import { handleEndEvaluat, handleStartEvaluat } from "./view/evaluating";
- import { IFingering, mappingVoicePart, subjectFingering, matchVoicePart } from "/src/view/fingering/fingering-config";
- import { handleStartTick } from "./view/tick";
- import { audioListStart, getAudioCurrentTime, getAudioDuration, setAudioCurrentTime, setAudioPlaybackRate, audioData } from "./view/audio-list";
- import { toggleFollow } from "./view/follow-practice";
- import { browser, setStorageSpeed, setGlobalData } from "./utils";
- import { api_cloudGetMediaStatus, api_createMusicPlayer, api_cloudChangeSpeed, api_cloudSuspend, api_cloudSetCurrentTime, api_cloudDestroy } from "./helpers/communication";
- import { verifyCanRepeat, getDuration } from "./helpers/formateMusic";
- import { getMusicSheetDetail } from "./utils/baseApi"
- import { getQuery } from "/src/utils/queryString";
- import { followData } from "/src/view/follow-practice/index"
- const query: any = getQuery();
- /** 入门 | 进阶 | 大师 */
- export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
- /** 渲染类型: 五线谱,简谱 */
- export enum EnumMusicRenderType {
- /** 五线谱 */
- staff = "staff",
- /** 简谱 */
- firstTone = "firstTone",
- /** 固定音高 */
- fixedTone = "fixedTone",
- }
- export const musicscoresettingKey = "musicscoresetting";
- /** 有声音的是那个音源 */
- export type IPlayState = "music" | "background";
- /** 播放状态 */
- export type IAudioState = "play" | "paused";
- /** 来源 */
- export enum IPlatform {
- APP = "APP",
- PC = "PC",
- }
- export type ISonges = {
- background?: string
- music?: string
- }
- /**
- * 特殊教材分类id
- */
- 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
- // 乐器code码
- export const musicalInstrumentCodeInfo = [
- {
- name: '长笛',
- code: 'Flute',
- id: 1
- },
- {
- name: '短笛',
- code: 'Piccolo',
- id: 2
- },
- {
- name: '单簧管',
- code: 'Clarinet',
- id: 3
- },
- {
- name: '低音单簧管',
- code: 'Bass Clarinet',
- id: 4
- },
- {
- name: '中音萨克斯',
- code: 'Alto Saxophone',
- id: 5
- },
- {
- name: '次中音萨克斯',
- code: 'Tenor Saxophone',
- id: 6
- },
- {
- name: '高音萨克斯',
- code: 'Soprano Saxophone',
- id: 7
- },
- {
- name: '上低音萨克斯',
- code: 'Baritone Saxophone',
- id: 8
- },
- {
- name: '双簧管',
- code: 'Oboe',
- id: 9
- },
- {
- name: '大管',
- code: 'Bassoon',
- id: 10
- },
- {
- name: '小号',
- code: 'Trumpet',
- id: 11
- },
- {
- name: '圆号',
- code: 'Horn',
- id: 12
- },
- {
- name: '长号',
- code: 'Trombone',
- id: 13
- },
- {
- name: '上低音号',
- code: 'Baritone',
- id: 14
- },
- {
- name: '次中音号',
- code: 'Euphonium',
- id: 15
- },
- {
- name: '大号',
- code: 'Tuba',
- id: 16
- },
- {
- name: '钢琴',
- code: 'Piano',
- id: 17
- },
- {
- name: '电钢琴',
- code: 'Electronical Piano',
- id: 18
- },
- {
- name: '钢片琴',
- code: 'Glockenspiel',
- id: 19
- },
- {
- name: '小提琴',
- code: 'Violin',
- id: 20
- },
- {
- name: '中提琴',
- code: 'Viola',
- id: 21
- },
- {
- name: '大提琴',
- code: 'Violoncello',
- id: 22
- },
- {
- name: '低音提琴',
- code: 'Contrabass',
- id: 23
- },
- {
- name: '架子鼓',
- code: 'Drum Set',
- id: 24
- },
- {
- name: '小鼓',
- code: 'Snare Drum',
- id: 25
- },
- {
- name: '马林巴',
- code: 'Marimba',
- id: 26
- },
- {
- name: '颤音琴',
- code: 'Vibraphone',
- id: 27
- },
- {
- name: '钟琴',
- code: 'Chimes',
- id: 28
- },
- {
- name: '木琴',
- code: 'Xylophone',
- id: 29
- },
- {
- name: '管钟',
- code: 'Tubular Bells',
- id: 30
- },
- {
- name: '定音鼓',
- code: 'Timpani',
- id: 31
- },
- {
- name: '键盘',
- code: 'Mallets',
- id: 32
- },
- {
- name: '排箫',
- code: 'Panpipes',
- id: 33
- },
- {
- name: '陶笛',
- code: 'Ocarina',
- id: 34
- },
- {
- name: '葫芦丝',
- code: 'Woodwind',
- id: 35
- },
- {
- name: '口风琴',
- code: 'Nai',
- id: 36
- },
- {
- name: '德式竖笛',
- code: 'Tenor Recorder',
- id: 37
- },
- {
- name: '英式竖笛',
- code: 'Baroque Recorder',
- id: 38
- },
- {
- name: '高音陶笛',
- code: 'Whistling',
- id: 39
- },
- ]
- const state = reactive({
- /** 来源 : PC , app */
- platform: "" as IPlatform,
- appName: "" as "GYM" | "COLEXIU",
- musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
- /**曲谱是否渲染完成 */
- musicRendered: false,
- /** 当前曲谱数据ID, 和曲谱ID不一致 */
- detailId: "",
- /** 曲谱资源URL */
- xmlUrl: "",
- /** 声部ID */
- subjectId: 0 as number,
- trackId: 0 as string | number,
- /** 分类ID */
- categoriesId: 0,
- /** 分类名称 */
- categoriesName: "",
- /** 是否支持评测 */
- enableEvaluation: true,
- /** 是否支持转谱 */
- enableNotation: false,
- /** 曲谱ID */
- examSongId: "",
- /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
- cbsExamSongId: "",
- /** 曲谱名称 */
- examSongName: "",
- /** 曲谱封面 */
- coverImg: "",
- /** 扩展字段 */
- extConfigJson: {} as any,
- /** 扩展样式字段 */
- extStyleConfigJson: {} as any,
- /** 是否开启节拍器(mp3节拍器) */
- isOpenMetronome: false,
- /** 是否显示指法 */
- isShowFingering: false,
- /** 原音 */
- music: "",
- /** 伴奏 */
- accompany: "",
- /** midiURL */
- midiUrl: "",
- /** 父分ID */
- parentCategoriesId: 0,
- /** 分类ID */
- musicSheetCategoriesId: 0,
- /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
- bizMusicCategoryId: 0,
- /** 资源类型: mp3 | midi */
- playMode: "MP3" as "MP3" | "MIDI",
- /** 设置的速度 */
- speed: 0,
- /** 曲谱音频正常的速度 */
- originSpeed: 0,
- /** 播放过程中显示的速度 */
- playIngSpeed: 0,
- /** 分轨名称 */
- track: "",
- /** 当前显示声部索引 */
- partIndex: 0,
- /** 是否需要节拍器 */
- needTick: false,
- /** 曲谱实例 */
- osmd: null as unknown as OpenSheetMusicDisplay,
- /**是否是特殊乐谱类型, 主要针对管乐迷 */
- isSpecialBookCategory: false,
- /** 播放状态 */
- playState: "paused" as IAudioState,
- /** 播放结束状态 */
- playEnd: false,
- /** 播放那个: 原音,伴奏 */
- playSource: "music" as IPlayState,
- /** 播放进度 */
- playProgress: 0,
- /** 激活的note index */
- activeNoteIndex: 0,
- /** 激活的小节 */
- activeMeasureIndex: 0,
- /** 选段状态 */
- sectionStatus: false,
- /** 选段数据 */
- section: [] as any[],
- /** 选段背景 */
- sectionBoundingBoxs: [] as any[],
- /** 开启选段预备 */
- isOpenPrepare: false,
- /** 选段预备 */
- sectionFirst: null as any,
- /** 音符数据 */
- times: [] as any[],
- /** 播放模式 */
- modeType: "practise" as "practise" | "follow" | "evaluating",
- /** 设置 */
- setting: {
- /** 效音提醒 */
- soundEffect: true,
- /** 护眼模式 */
- eyeProtection: false,
- /** 摄像头 */
- camera: false,
- /** 摄像头透明度 */
- cameraOpacity: 70,
- /** 循环播放 */
- repeatAutoPlay: true,
- /** 显示指法 */
- displayFingering: true,
- /** 显示光标 */
- displayCursor: true,
- /** 频率 */
- frequency: 0,
- /** 评测难度 */
- evaluationDifficulty: "BEGINNER" as IDifficulty,
- /** 保存到相册 */
- saveToAlbum: true,
- /** 开启伴奏 */
- enableAccompaniment: true,
- /** 反应时间 */
- reactionTimeMs: 0,
- /** 节拍器音量 */
- beatVolume: 50,
- },
- /** 后台设置的基准评测频率 */
- baseFrequency: 440,
- /** mp3节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
- fixtime: 0,
- /** evxml等待播放的时间 */
- evXmlBeginTime: 0,
- /** 指法信息 */
- fingeringInfo: {} as IFingering,
- /** 滚动容器的ID */
- scrollContainer: "musicAndSelection",
- /** 是否是打击乐 */
- isPercussion: false,
- /** 评测标准 */
- evaluationStandard: '',
- /** 是否重复节拍器的时间 */
- repeatedBeats: 0,
- /**当前曲谱中所有声部名字 */
- partListNames: [] as any,
- /** 渐变速度信息 */
- gradual: [] as GradualNote[],
- /** 渐变速度版本 */
- gradualVersion: GradualVersion.BASE as GradualVersion,
- /** 渐变时间信息 */
- gradualTimes: null as GradualTimes,
- /** 单声部多声轨 */
- multitrack: 0,
- /** 缩放 */
- zoom: 0.8,
- /** 渲染曲谱比例 */
- musicZoom: 1,
- /** 练习,评测是否是选段模式 */
- isSelectMeasureMode: false,
- /** 是否是评分显示 */
- isReport: false,
- /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
- isHideEvaluatReportSaveBtn: false,
- /** 是否是合奏 */
- isConcert: false,
- /** 用户选择的结束小节数 */
- userChooseEndIndex: 0,
- /** 重播小节集合信息 */
- repeatInfo: [] as any,
- /** 多分轨的曲子,可支持筛选的分轨 */
- canSelectTracks: [] as any,
- /** 声部codeId */
- subjectCodeId: 0 as number,
- /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
- musicalCodeId: 0 as number,
- /** 乐器code,用于评测传参 */
- musicalCode: '' as any,
- /** 合奏曲目是否合并展示 */
- isCombineRender: false,
- /** 小节的持续时长,以后台设置的播放速度计算 */
- measureTime: 0,
- /** 跟练模式,节拍器播放的时间 */
- beatStartTime: 0,
- /** 是否为详情预览模式 */
- isPreView: false,
- /** 是否为评测报告模式 */
- isEvaluatReport: false,
- /** midi播放器是否初始化中 */
- midiPlayIniting: false,
- /** 曲目信息 */
- songs: {} as ISonges,
- isAppPlay: false, // 是否midi音频,midi是app播放
- /** 音频播放器实例 */
- audiosInstance: null as any,
- /** midi音频的时长 */
- durationNum: 0,
- midiSectionStart: 0,
- /** 音频文件是否加载完成 */
- audioDone: false,
- /** 谱面svgdom节点 */
- osmdSvgDom: null as any,
- /** 滚动容器dom */
- osdmScrollDom: null as any,
- /** 光标dom */
- cursorDom: null as any,
- fistNoteLeft: 0,
- /** 是否为单行谱渲染模式 */
- isSingleLine: false,
- /** 首尾音符的间距 */
- noteDistance: 0,
- /** 一行谱运动模式,平滑移动、匀速移动 */
- moveType: "smooth" as "smooth" | "uniform",
- /** 是否是evxml */
- isEvxml: false,
- noTimes: [] as any,
- attendHideMenu: true,
- /** 老师端:功能按钮布局方向 */
- playBtnDirection: "left" as "left" | "right",
- /** 云教练按钮方向,如果有指法并且是竖向的指法,为了防止播放按钮把指法挡住,此时云教练播放按钮方向应该取反 */
- musicScoreBtnDirection: "right" as "left" | "right",
- /** 引导页信息 */
- guideInfo: null as any,
- });
- const browserInfo = browser();
- let offset_duration = 0;
- /** 自定义数据 */
- export const customData = reactive({
- /** 自定义音符时值 */
- customNoteRealValue: [] as any,
- /** 自定义音符按读取到的时值 */
- customNoteCurrentTime: false,
- });
- /** 在渲染前后计算光标应该走到的音符 */
- const setStep = () => {
- // console.log('播放状态',state.playState)
- if (state.playState !== "play") {
- console.log("暂停播放");
- return;
- }
- let startTime = Date.now();
- requestAnimationFrame(() => {
- const endTime = Date.now();
- // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
- if (endTime - startTime < 16.7) {
- handlePlaying();
- setStep();
- } else {
- setTimeout(() => {
- handlePlaying();
- setStep();
- }, 16.7);
- }
- });
- };
- /** 开始播放 */
- export const onPlay = () => {
- console.log("开始播放");
- state.playEnd = false;
- // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
- offset_duration = 0.2;
- setStep();
- };
- /** 播放模式结束自动重播 */
- const autoResetPlay = () => {
- if (state.modeType !== "practise") return;
- skipNotePlay(0, true);
- // 没有开启自动重播, 不是练习模式
- if (!state.setting.repeatAutoPlay) return;
- scrollViewNote();
- setTimeout(() => {
- togglePlay("play");
- }, 1000);
- };
- /** 播放完成事件 */
- export const onEnded = () => {
- console.log("音频播放结束");
- // if (state.isAppPlay) {
- // // 销毁播放器
- // api_cloudDestroy();
- // }
- // 修改状态为结束
- state.playEnd = true;
- state.playState = "paused";
- // 结束播放
- audioListStart(state.playState);
- // 调用结束评测
- handleEndEvaluat(true);
- // 调用自动重复播放
- autoResetPlay();
- };
- /**
- * 播放一直触发的事件
- */
- const handlePlaying = () => {
- const currentTime = getAudioCurrentTime();
- const duration = getAudioDuration();
- state.playProgress = (currentTime / duration) * 100;
- let item = getNote(currentTime);
- // console.log(11111,currentTime,duration,state.playSource, item)
- // console.log(item.i,item.noteId,item.measureSpeed)
- // 练习模式下,实时刷新小节速度
- if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
- const ratio = state.speed / state.originSpeed
- state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
- } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
- state.playIngSpeed = state.speed
- }
- if (item) {
- // 选段状态下
- if (state.sectionStatus && state.section.length === 2) {
- // 如果开启了预备拍
- const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
- const selectEndItem = state.section[1];
- /**
- * #9374,反复小节的曲目播放错误, bug修复
- * 曲目:噢!苏珊娜-排箫-人音
- * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
- * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
- */
- if (state.repeatInfo.length) {
- const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
- const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
- if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
- const preItem = state.times[item.i - 1]
- if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
- const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
- if (skipItem) {
- // 跳转到指定的音频位置
- setAudioCurrentTime(skipItem.time, skipItem.i);
- gotoNext(skipItem);
- return
- }
- }
- }
- }
- // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
- // if (currentTime - selectEndItem.endtime > offset_duration) {
- //console.log(currentTime,selectEndItem.endtime)
- if (currentTime - selectEndItem.endtime >= 0) {
- console.log("选段播放结束",state.setting.repeatAutoPlay);
- // 如果为选段评测模式
- if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
- onEnded();
- return;
- }
- // #8698 bug修复
- if (state.modeType === "practise" && state.sectionStatus) {
- onEnded();
- resetPlaybackToStart();
- return;
- }
- item = selectStartItem;
- setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
- }
- }
- gotoNext(item);
- }
- // 评测不播放叮咚节拍器
- // if (state.modeType !== "evaluating") {
- // metronomeData.metro?.sound(currentTime);
- // }
- metronomeData.metro?.sound(currentTime);
- // 一行谱,需要滚动小节
- if (state.isSingleLine) {
- if (state.moveType === 'smooth') {
- smoothMoveSvgDom();
- } else {
- uniformMoveSvgDom();
- }
- }
-
- };
- /** 跳转到指定音符开始播放 */
- export const skipNotePlay = async (itemIndex: number, isStart = false) => {
- const item = state.times[itemIndex];
- let itemTime = item.time;
- if (isStart) {
- itemTime = 0;
- }
- if (item) {
- setAudioCurrentTime(itemTime, itemIndex);
- // 一行谱,点击音符,或者播放完成,需要跳转音符位置
- gotoNext(item, true);
- metronomeData.metro?.sound(itemTime);
- if (state.isAppPlay) {
- await api_cloudSetCurrentTime({
- currentTime: itemTime * 1000,
- songID: state.examSongId,
- })
- audioData.progress = itemTime
- state.midiSectionStart = itemTime
- }
- }
- };
- /**
- * 切换曲谱播放状态
- * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
- */
- export const togglePlay = async (playState?: "play" | "paused") => {
- // 如果mp3资源还在加载中,给出提示
- if (!state.isAppPlay && !state.audioDone) {
- showToast('音频资源加载中,请稍后')
- return
- }
- // midi播放
- if (state.isAppPlay) {
- if( playState === "paused" ) {
- await api_cloudSuspend({
- songID: state.examSongId,
- })
- state.playState = 'paused'
- return
- }
- skipNotePlay(state.activeNoteIndex, false);
- await api_cloudChangeSpeed({
- speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
- originalSpeed: state.originSpeed,
- songID: state.examSongId,
- });
- const cloudGetMediaStatus = await api_cloudGetMediaStatus();
- const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
- state.playState = status
- } else {
- state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
- }
- if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
- resetPlaybackToStart();
- }
- // 设置为开始播放时, 如果需要节拍,先播放节拍器
- if (state.playState === "play" && state.needTick) {
- const tickend = await handleStartTick();
- // console.log("🚀 ~ tickend:", tickend)
- // 节拍器返回false, 取消播放
- if (!tickend) {
- state.playState = "paused";
- return false;
- }
- }
- // 如果选段没有结束, 直接开始播放,清空选段状态
- if (state.playState == "play") {
- if (state.sectionStatus && state.section.length < 2) {
- clearSelection();
- }
- }
- audioListStart(state.playState);
- return true;
- };
- /** 结束播放 */
- export const handleStopPlay = () => {
- state.playState = "paused";
- audioListStart(state.playState);
- };
- /** 重置播放为开始 */
- export const resetPlaybackToStart = () => {
- // 如果为选段状态
- if (state.sectionStatus && state.section.length === 2) {
- state.section = formateSelectMearure(state.section);
- return;
- } else {
- // 非选段状态,重播需要重置当前选中的小节为第一个小节
- metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
- }
- skipNotePlay(0, true);
- };
- /** 跳转到指定音符 */
- export const gotoCustomNote = (index: number) => {
- try {
- state.osmd.cursor.reset();
- } catch (error) {}
- for (let i = 0; i < index; i++) {
- state.osmd.cursor.next();
- }
- };
- const setCursorPosition = (note: any, cursor: any) => {
- if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
- /**
- * bug:#9920、#9940
- * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
- */
- if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
- return
- }
- nextTick(() => {
- let bbox = note.bbox;
- if (!bbox) {
- const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
- x: 0,
- y: 0,
- };
- const parentLeft = musicContainer.x || 0;
- const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
- if (noteEle) {
- const noteHead = noteEle.querySelector(".vf-numbered-note-head");
- const noteHeadBbox = noteHead?.getBoundingClientRect?.();
- if (noteHeadBbox) {
- note.bbox = {
- left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
- width: noteHeadBbox.width * 1.5,
- };
- bbox = note.bbox;
- }
- }
- }
- if (!bbox) return;
- const baseW = state.platform === IPlatform.PC ? 29 : 18;
- const width = (bbox.width - baseW) / 3;
- // console.log(555555,bbox.left,width)
- cursor.cursorElement.style.left = bbox.left + "px";
- cursor.cursorElement.style.transform = `translateX(${width}px)`;
- });
- }
- };
- /**
- * 跳转到下一个音符
- * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
- **/
- export const gotoNext = (note: any, skipNote?: boolean) => {
- // console.log(33333333333,state.activeNoteIndex,note.i)
- const num = note.i;
- if (state.activeNoteIndex === note.i) {
- try {
- setCursorPosition(note, state.osmd.cursor);
- } catch (error) {
- console.log(error);
- }
- return;
- }
- const osmd = state.osmd;
- let prev = state.activeNoteIndex;
- state.activeNoteIndex = num;
- state.activeMeasureIndex = note.MeasureNumberXML;
- if (prev && num - prev === 1) {
- osmd.cursor.next();
- } else if (prev && num - prev > 0) {
- while (num - prev > 0) {
- prev++;
- osmd.cursor.next();
- }
- } else {
- gotoCustomNote(num);
- }
- try {
- setCursorPosition(note, state.osmd.cursor);
- } catch (error) {
- console.log(error);
- }
- // 一行谱,需要滚动小节
- if (state.isSingleLine) {
- moveSvgDom(skipNote);
- }
- scrollViewNote();
- };
- /** 获取指定音符 */
- export const getNote = (currentTime: number) => {
- const times = state.times;
- const len = state.times.length;
- /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
- if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
- onEnded();
- return;
- }
- let _item = null as any;
- for (let i = state.activeNoteIndex; i < len; i++) {
- const item = times[i];
- const prevItem = times[i - 1];
- if (currentTime >= item.time) {
- if (!prevItem || item.time != prevItem.time) {
- _item = item;
- }
- } else {
- break;
- }
- }
- // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
- return _item;
- };
- /** 重播 */
- export const handleResetPlay = () => {
- // 如果是midi需要重置播放进度
- if (state.isAppPlay) {
- audioData.progress = 0
- }
- resetPlaybackToStart();
- // 如果是暂停, 直接播放
- togglePlay("play");
- };
- /** 设置速度 */
- export const handleSetSpeed = (speed: number) => {
- setStorageSpeed(state.examSongId, speed);
- state.speed = speed;
- };
- /** 清除选段状态 */
- export const clearSelection = () => {
- state.sectionStatus = false;
- state.section = [];
- closeToast();
- };
- /** 开启选段 */
- export const handleChangeSection = () => {
- // 如果开启了选段,再次点击取消选段
- if (state.sectionStatus) {
- togglePlay("paused");
- clearSelection();
- skipNotePlay(0, true);
- state.sectionFirst = null;
- return;
- }
- state.sectionStatus = true;
- // 开启
- if (state.sectionStatus) {
- togglePlay("paused");
- }
- showToast({
- message: "请选择开始小节",
- duration: 0,
- position: "top",
- className: "selectionToast",
- });
- };
- /** 效验并格式化选段小节 */
- const formateSelectMearure = (_list: any[]): any[] => {
- if (!_list.length) return [];
- const list = _list.sort((a, b) => a.time - b.time);
- const startXml = list[0]?.measureOpenIndex;
- const endXml = list.last()?.measureOpenIndex;
- const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
- const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
- // 没有找到选段小节
- if (!selectStartMeasure.length || !selectEndMeasure.length) {
- clearSelection();
- return [];
- }
- list[0] = selectStartMeasure[0];
- list[1] = selectEndMeasure.last();
- let startItemINdex = list[0].i;
- // 开启预备拍
- if (state.isOpenPrepare) {
- const startXmlIndex = list[0].MeasureNumberXML;
- state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
- startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
- }
- skipNotePlay(startItemINdex, startItemINdex === 0);
- return list;
- };
- /** 选择选段 */
- export const handleSelection = (item: any) => {
- if (!state.sectionStatus || state.section.length > 1) return;
- if (state.section.length !== 2 && item) {
- state.section.push(item);
- if (state.section.length === 2) {
- setSection(state.section[0].MeasureNumberXML,state.section[1].MeasureNumberXML)
- //state.section = formateSelectMearure(state.section);
- closeToast();
- }
- }
- if (state.section.length === 1) {
- showToast({
- message: "请选择结束小节",
- duration: 0,
- position: "top",
- className: "selectionToast",
- });
- }
- };
- /** 阶段练习、阶段评测设置选段小节 */
- export const setSection = (start: number, end: number, userSpeed?: number) => {
- const startNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
- )
- const endNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
- )
- state.userChooseEndIndex = end
- const lastEndId = endNotes[endNotes.length - 1].noteId
- let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
- // 是否符合重播规则
- const canRepeatInfo = verifyCanRepeat(start, end)
- console.log('能否重播',canRepeatInfo)
- const isCanRepeat = canRepeatInfo.canRepeat
- // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
- /**
- * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
- * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
- * TODO:通过vf-volta判断是否是跳房子
- */
- let isSkipVolta = false; // 结束小节是否是跳房子小节
- if (lastEndNotes.length === 1) {
- isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
- }
- let currentEndNum: number = end
- const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
- while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
- currentEndNum = currentEndNum - 1
- const newEndNotes = state.times.filter(
- (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
- )
- const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
- lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
- }
- const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
- const startNote = startNotes[0]
- // const endNote = endNotes[endNotes.length - 1]
- const endNote = lastEndNotes[endIdx]
-
- if (startNote && endNote) {
- state.isSelectMeasureMode = true;
- // 设置小节
- hanldeDirectSelection([startNote, endNote]);
- //设置速度
- if (userSpeed) {
- handleSetSpeed(userSpeed);
- }
- }
- }
- /** 直接设置选段 */
- export const hanldeDirectSelection = (list: any[]) => {
- if (!Array.isArray(list) || list.length !== 2) return;
- state.sectionStatus = true;
- setTimeout(() => {
- state.section = formateSelectMearure(list);
- console.log('选段小节',state.section)
- }, 500);
- };
- let offsetTop = 0;
- /**
- * 窗口内滚动到音符的区域
- * @param isScroll 可选: 强制滚动到顶部, 默认: false
- * @returns void
- */
- export const scrollViewNote = () => {
- const cursorElement = document.getElementById("cursorImg-0")!;
- const musicAndSelection = document.getElementById(state.scrollContainer)!;
- if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
- offsetTop = cursorElement.offsetTop;
- if (offsetTop > 50) {
- musicAndSelection.scrollTo({
- top: (offsetTop - 50) * state.musicZoom,
- behavior: "smooth",
- });
- } else {
- musicAndSelection.scrollTo({
- top: 0,
- behavior: "smooth",
- });
- }
- };
- /** 检测是否是节奏练习 */
- export const isRhythmicExercises = () => {
- return state.examSongName.indexOf("节奏练习") > -1;
- };
- /** 重置状态 */
- export const handleRessetState = () => {
- // 切换模式,清除选段
- clearSelection();
- skipNotePlay(0, true);
- // midi 重置播放进度
- if (state.isAppPlay) {
- audioData.progress = 0;
- }
- if (state.modeType === "evaluating") {
- handleStartEvaluat();
- } else if (state.modeType === "practise") {
- togglePlay("paused");
- } else if (state.modeType === "follow") {
- toggleFollow(false);
- }
- };
- export default state;
- /** 初始化评测音频 */
- export const evaluatCreateMusicPlayer = () => {
- return api_createMusicPlayer({
- musicSrc: state.accompany || state.music, // 曲谱音频url
- tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
- });
- };
- /** 获取内容平台的接口详情并初始化state信息 */
- export const getMusicDetail = async (id: string) => {
- const res = await getMusicSheetDetail(id);
- if (res?.code === 200) {
- getMusicInfo(res)
- }
- };
- const getMusicInfo = (res: any) => {
- const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
- // 原音声轨
- const musicData = res.data.musicSheetSoundList?.[index] || {};
- // 伴奏声轨
- const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
- const musicInfo = {
- ...res.data,
- music: musicData.audioFileUrl || '',
- accompany: accompanyData.audioFileUrl || '',
- musicSheetId: musicData.musicSheetId || res.data.bizId,
- track: musicData.track || '',
- };
- console.log("🚀 ~ musicInfo:", musicInfo);
- setState(musicInfo, index);
- };
- const setState = (data: any, index: number) => {
- state.appName = "COLEXIU";
- state.detailId = data.bizId;
- state.xmlUrl = data.xmlFileUrl;
- state.partIndex = index;
- state.trackId = data.track;
- state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
- // 声部code
- const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
- // 乐器code
- let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
- const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
- const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
- state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
- state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
- state.categoriesId = data.musicCategoryId;
- state.categoriesName = data.musicTagNames;
- // state.enableEvaluation = data.isEvaluated ? true : false;
- state.examSongId = data.bizId + "";
- state.cbsExamSongId = data.id + "";
- state.examSongName = data.name;
- state.coverImg = data.musicCover ?? "";
- // 单声部多声轨合并展示
- state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
- setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
- // 解析扩展字段
- if (data.extConfigJson) {
- try {
- state.extConfigJson = JSON.parse(data.extConfigJson as string);
- } catch (error) {
- console.error("解析扩展字段错误:", error);
- }
- }
- state.gradualTimes = state.extConfigJson.gradualTimes;
- state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
- state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
- // 曲子包含节拍器,就不开启节拍器
- state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
- // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
- state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
- state.isShowFingering = data.isShowFingering ? true : false;
- // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
- state.isAppPlay = data.playMode === 'MIDI';
- state.music = data.music;
- state.accompany = data.accompany;
- state.midiUrl = data.midiFileUrl;
- state.parentCategoriesId = data.musicTag;
- state.musicSheetCategoriesId = data.musicCategoryId;
- state.bizMusicCategoryId = data.bizMusicCategoryId
- state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
- state.originSpeed = state.speed = data.playSpeed;
- // state.playIngSpeed = data.playSpeed;
- const track = data.code || data.track;
- state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
- // 能否评测,根据当前声轨有无伴奏判断
- if (state.isAppPlay) {
- state.enableEvaluation = state.midiUrl ? true : false
- } else {
- state.enableEvaluation = state.accompany ? true : false
- }
- state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
- // multiTracksSelection 返回为空,默认代表全部分轨
- state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
- // 开启预备小节
- state.isOpenPrepare = true;
- state.extStyleConfigJson = data.extStyleConfigJson || {}
- // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
- // 是否打击乐
- /**
- * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
- * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
- * 打击乐&节奏练习,没有跟练模式
- */
- // state.isPercussion = isRhythmicExercises();
- state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
- state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
- // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
- state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
- // 设置指法
- // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
- /**
- * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
- * 获取指法code
- */
- const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
- state.fingeringInfo = subjectFingering(code);
- console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
- state.musicalCodeId = state.fingeringInfo?.id || 0
- state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
- ;(window as any).DYSubjectId = state.musicalCodeId
- // 开启自定义每行显示的小节数
- ;(window as any).customSectionAmount = true
- // 标识是课堂乐器,用于移调时进行区分处理
- ;(window as any).DYProjectName = 'musicScore';
- // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
- if (!state.fingeringInfo.name && state.setting.displayFingering) {
- state.setting.displayFingering = false
- }
- // 检测是否原音和伴奏都有
- if (!state.music || !state.accompany) {
- state.playSource = state.music ? "music" : "background";
- }
- // 如果是PC端,放大曲谱
- state.platform = query.platform?.toLocaleUpperCase() || "";
- if (state.platform === IPlatform.PC) {
- state.zoom = query.zoom || 1.5;
- state.enableEvaluation = false;
- }
- /**
- * 默认渲染什么谱面类型 & 能否转谱逻辑
- * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
- * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
- *
- */
- let pitchTrack = null
- if (state.isConcert) {
- musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
- pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
- } else {
- pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
- }
- let musicalRenderType = ''
- if (pitchTrack?.defaultScore) {
- musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
- }
- state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
- state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
- console.log("state对象", state);
- // 评测基准频率
- state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
- state.baseFrequency = Number(state.baseFrequency)
- // 用户上次的频率和基准频率误差超过10,则重置
- if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
- state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
- } else {
- state.setting.frequency = state.setting.frequency || state.baseFrequency
- }
- };
- // 多分轨合并显示标示
- const setCustom = (trackNum?: number) => {
- if (trackNum || state.extConfigJson.multitrack) {
- state.multitrack = trackNum || 0
- setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
- }
- };
- /** 跟练模式播放节拍器(叮咚) */
- export const followBeatPaly = () => {
- let metroTimer: any = null;
- if (!followData.start) {
- clearTimeout(metroTimer)
- metroTimer = null
- return;
- }
- const time = state.measureTime*1000 / metronomeData.totalNumerator
- requestAnimationFrame(() => {
- const endTime = Date.now();
- if (endTime - state.beatStartTime < time) {
- followBeatPaly();
- } else {
- // metroTimer = setTimeout(() => {
- // metronomeData.metro?.simulatePlayAudio()
- // startTime = Date.now();
- // followBeatPaly();
- // }, time);
- metronomeData.metro?.simulatePlayAudio()
- state.beatStartTime = Date.now();
- followBeatPaly();
- }
- });
- };
- // 音符添加bbox
- export const addNoteBBox = (list: any[]) => {
- let voicesBBox: any = null;
- for (let i = 0; i < list.length; i++) {
- const note = list[i];
- const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
- /**
- * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
- */
- let bbox: any = null;
- if (svgElement?.attrs.id) {
- // @ts-ignore
- bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
- bbox = {
- x: bbox?.x * state.zoom,
- y: bbox?.y * state.zoom,
- width: bbox?.width * state.zoom,
- height: bbox?.height * state.zoom,
- }
- } else {
- // @ts-ignore
- let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
- const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
- if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
- currentVoicesBBox = voicesBBox;
- }
- let nextIndex = i + 1;
- while (!list[nextIndex]?.id && nextIndex < list.length) {
- nextIndex += 1;
- }
- // 休止小节的开头和下一个音符之间的间距
- let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
- if (list[nextIndex]?.id) {
- // @ts-ignore
- multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
- }
- const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
- bbox = currentVoicesBBox ? {
- bottom: currentVoicesBBox.bottom,
- height: 30,
- left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
- right: currentVoicesBBox.y,
- top: currentVoicesBBox.top,
- width: 1,
- x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
- y: currentVoicesBBox.y,
- svgBodyLeft: svgBodyBBox?.x,
- } : null;
- voicesBBox = currentVoicesBBox;
- }
- note.bbox = bbox;
- }
- }
- // 一行谱模式,创建固定的光标
- export const createFixedCursor = () => {
- if (!state.isSingleLine) return;
- const svg: any = document.getElementById("osmdSvgPage1");
- state.osmdSvgDom = svg;
- const scrollDom = document.getElementById("musicAndSelection");
- const cursorDom = document.getElementById("cursorImg-0");
- state.fistNoteLeft = cursorDom?.getBoundingClientRect()?.left || 0;
- state.osdmScrollDom = scrollDom;
- state.cursorDom = cursorDom;
- let copyCursor: any = cursorDom?.cloneNode(true);
- if (copyCursor) {
- copyCursor.setAttribute('id','cursor-copy');
- copyCursor.style.position = 'sticky';
- copyCursor.style.zIndex = '2';
- // if (!state.times[0]?.id) {
- // copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 3 + 'px';
- // }
- copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 2 - 1 + 'px';
- copyCursor.style.height = parseFloat(copyCursor.style.height) * 3 + 'px';
- copyCursor.style.opacity = state.moveType === 'uniform' ? 0 : 1;
- // copyCursor.style.background = 'red';
- copyCursor && scrollDom?.appendChild(copyCursor);
- // 创建左侧背景dom
- // @ts-ignore
- const firstMeasureBBox: any = document.querySelector('.vf-measure')?.getBBox();
- const leftDom = document.createElement("div");
- leftDom.style.width = state.times[0]?.bbox?.x - firstMeasureBBox?.x * state.zoom + 'px';
- leftDom.style.height = firstMeasureBBox?.height * state.zoom + 'px';
- leftDom.style.left = firstMeasureBBox?.x * state.zoom + 'px';
- leftDom.style.transform = 'translateY(20px)';
- leftDom.classList.add('leftNoteBg');
- // scrollDom?.appendChild(leftDom);
- }
- }
- /** 计算首尾音符的间距 */
- export const calculateDistance = () => {
- const firstNoteBBox = state.times[0]?.bbox;
- const lastNoteBBox = state.times.last()?.bbox;
- if (firstNoteBBox && lastNoteBBox) {
- const noteDistance = lastNoteBBox.x - firstNoteBBox.x + lastNoteBBox.width / 2 - firstNoteBBox.width / 2 - 1;
- console.log('首尾间距', noteDistance)
- state.noteDistance = noteDistance || 0;
- }
- }
- /** 跳动svgdom */
- export const moveSvgDom = (skipNote?: boolean) => {
- // const cursorLeft = state.cursorDom?.getBoundingClientRect()?.left || 0;
- // const leftValue = parseFloat(state.cursorDom.style.left) - 47 - 20;
- // console.log(cursorLeft,leftValue,'光标位置')
- // state.osmdSvgDom.style.transform = `translateX(${-leftValue}px)`;
- // state.osdmScrollDom.scrollLeft = leftValue
- // console.log('当前音符',state.activeNoteIndex)
- state.times.forEach((item: any, idx: number) => {
- const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
- const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
- if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
- svgEl?.classList.add('noteActive')
- stemEl?.classList.add('noteActive')
- } else {
- svgEl?.classList.remove('noteActive')
- stemEl?.classList.remove('noteActive')
- }
- })
- // document.getElementById('cursor-copy')?.classList.add('cursorAnimate');
- /**
- * 计算需要移动的距离
- * 当前选中的音符和第一个音符之间的间距
- */
- if (skipNote) {
- const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 2 - state.times[0].bbox?.width / 2;
- state.osdmScrollDom.scrollTo({
- left: distance,
- behavior: "smooth",
- });
- }
- }
- /** 平滑移动svgdom */
- export const smoothMoveSvgDom = () => {
- const currentTime = getAudioCurrentTime();
- const matchNoteIdx = state.times.findIndex((item: any) => Math.abs(item.time - currentTime) * 1000 < 100 )
- // if (matchNoteIdx >= 0) {
- // console.log('匹配',matchNoteIdx,currentTime)
- // }
-
- if (currentTime <= state.fixtime) return;
- if (currentTime > state.times.last()?.time) return;
- // console.log('跳转音符',currentTime)
- const currentBBox = state.times[state.activeNoteIndex]?.bbox;
- let nextIndex = state.activeNoteIndex + 1;
- let nextBBox = state.times[nextIndex]?.bbox;
- while (!nextBBox && nextIndex < state.times.length) {
- nextIndex += 1;
- nextBBox = state.times[nextIndex]?.bbox;
- }
- // 下一个音符和当前播放音符之间的间距
- let noteDistance = nextBBox?.x - state.times[state.activeNoteIndex].bbox?.x + nextBBox?.width / 4 - state.times[state.activeNoteIndex].bbox?.width / 4 || 0
- if (noteDistance) {
- // 当前的音符和下一个音符之间的时值
- const noteDuration = state.times[nextIndex].time - state.times[state.activeNoteIndex]?.time;
- // 当前时值在该区间的占比
- const playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration;
- // 如果当前播放的音符是休止小节的,实际没有音符
- // if (!state.times[state.activeNoteIndex]?.id && state.times[state.activeNoteIndex]?.multipleRestMeasures && state.times[state.activeNoteIndex+1].id) {
- // noteDistance = noteDistance - state.times[state.activeNoteIndex]?.bbox?.svgBodyLeft;
- // }
- const distance = noteDistance * playProgress;
-
- // 上一个音符和第一个音符的间距
- let preDistance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 4;
- // console.log(state.activeNoteIndex,'滑动', distance, preDistance, state.osdmScrollDom.scrollLeft, noteDistance, nextIndex, currentTime, noteDuration )
- // console.log('当前音符',state.activeNoteIndex,'距离',noteDistance,'比例',playProgress,'上一个距离',preDistance,'时值',currentTime, noteDuration)
- //console.log('滑动','音符:',state.activeNoteIndex,'小节:', state.activeMeasureIndex)
- state.osdmScrollDom.scrollLeft = distance + preDistance;
- } else {
- const playProgress = (currentTime - state.times[0]?.time) / state.times.last()?.time
- const distance = state.noteDistance * playProgress;
- state.osdmScrollDom.scrollLeft = distance;
- }
- }
- // 匀速平移
- export const uniformMoveSvgDom = () => {
- const currentTime = getAudioCurrentTime();
- if (currentTime <= state.fixtime) return;
- if (currentTime > state.times.last()?.time) return;
- const playProgress = (currentTime - state.fixtime) / state.times.last()?.time;
- const distance = playProgress * state.noteDistance || 0;
- state.osdmScrollDom.scrollLeft = distance;
- }
|