index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { defineComponent, onMounted, onUnmounted, reactive, ref, watch } from "vue";
  2. import state, { gotoNext, resetPlaybackToStart, followBeatPaly, skipNotePlay, initSetPlayRate } from "/src/state";
  3. import { IPostMessage } from "/src/utils/native-message";
  4. import { api_cloudFollowTime, api_cloudToggleFollow } from "/src/helpers/communication";
  5. import { storeData } from "/src/store";
  6. import { audioRecorder } from "./audioRecorder";
  7. import { handleStartTick } from "/src/view/tick";
  8. import { metronomeData } from "/src/helpers/metronome";
  9. import { getDuration } from "/src/helpers/formateMusic";
  10. import { OpenSheetMusicDisplay } from "/osmd-extended/src";
  11. import { browser, getBehaviorId } from "/src/utils";
  12. import { api_musicPracticeRecordSave } from "../../page-instrument/api";
  13. import { getQuery } from "/src/utils/queryString";
  14. import { getAudioDuration } from "/src/view/audio-list";
  15. const query: any = getQuery();
  16. export const followData = reactive({
  17. list: [] as any, // 频率列表
  18. index: 0,
  19. start: false,
  20. rendered: false,
  21. /** 麦克风权限 */
  22. earphone: false,
  23. isBeginMask: false, // 倒计时和系统节拍器时候的遮罩,防止用户点击
  24. dontAccredit: true, // 没有开启麦克风权限,不需要调用结束收音的api
  25. practiceStart: false,
  26. });
  27. // 记录跟练时长
  28. const handleRecord = (total: number) => {
  29. if (query.isCbs) return
  30. if (total < 0) total = 0;
  31. const totalTime = total / 1000;
  32. const rate = state.basePlayRate * state.originAudioPlayRate; // 播放倍率
  33. // 如果是选段,则选选段开头小节的速度
  34. const currentSpeed = state.sectionStatus && state.section.length === 2 && state.section[0].measureSpeed ? state.section[0].measureSpeed * state.basePlayRate : state.speed;
  35. const body = {
  36. clientType: storeData.user.clientType,
  37. musicSheetId: state.examSongId,
  38. sysMusicScoreId: state.examSongId,
  39. feature: "FOLLOW_UP_TRAINING",
  40. practiceSource: "FOLLOW_UP_TRAINING",
  41. playTime: totalTime,
  42. deviceType: browser().android ? "ANDROID" : "IOS",
  43. behaviorId: getBehaviorId(),
  44. sourceTime: getAudioDuration(), // 音频时长
  45. instrumentId: state.instrumentId,
  46. playRate: rate,
  47. partIndex: state.partIndex, // 音轨
  48. speed: currentSpeed, // 速度
  49. };
  50. api_musicPracticeRecordSave(body);
  51. };
  52. /** 点击跟练模式 */
  53. export const toggleFollow = (notCancel = true) => {
  54. state.modeType = state.modeType === "follow" ? "practise" : "follow";
  55. // 取消跟练
  56. if (!notCancel) {
  57. followData.start = false;
  58. followData.practiceStart = false;
  59. // 开启了麦克风授权,才需要调用结束收音
  60. if (storeData.isApp && !followData.dontAccredit) {
  61. openToggleRecord(false);
  62. }
  63. }
  64. };
  65. const noteFrequency = ref(0);
  66. const audioFrequency = ref(0);
  67. const followTime = ref(0);
  68. // 切换录音
  69. const openToggleRecord = async (open: boolean = true) => {
  70. if (!open) api_cloudToggleFollow(open ? "start" : "end");
  71. // 记录跟练时长
  72. if (open) {
  73. followTime.value = Date.now();
  74. } else {
  75. const playTime = Date.now() - followTime.value;
  76. if (followTime.value !== 0 && playTime > 0) {
  77. handleRecord(playTime);
  78. followTime.value = 0;
  79. }
  80. }
  81. if (!storeData.isApp) {
  82. const openState = await audioRecorder?.toggleRecord(open);
  83. // 开启录音失败
  84. if (!openState && followData.start) {
  85. followData.earphone = true;
  86. followData.start = false;
  87. followData.practiceStart = false;
  88. }
  89. }
  90. };
  91. // 清除音符状态
  92. const onClear = () => {
  93. state.times.forEach((item: any) => {
  94. const note: HTMLElement = document.querySelector(`div[data-vf=vf${item.id}]`)!;
  95. if (note) {
  96. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  97. }
  98. const _note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  99. const stemEl = document.getElementById(`vf-${item.id}-stem`);
  100. if (_note) {
  101. _note.classList.remove("follow-up", "follow-down", "follow-success");
  102. stemEl?.classList.remove("follow-up", "follow-down", "follow-success");
  103. }
  104. });
  105. };
  106. /** 开始跟练 */
  107. export const handleFollowStart = async () => {
  108. followData.isBeginMask = true
  109. checking = false;
  110. const res = await api_cloudToggleFollow("start");
  111. // 用户没有授权,需要重置状态
  112. if (res?.content?.reson) {
  113. followData.isBeginMask = false
  114. followData.start = false;
  115. followData.practiceStart = false;
  116. } else {
  117. followData.dontAccredit = false;
  118. // 从头开始跟练,跟练模式开始前,增加播放系统节拍器
  119. if (state.activeNoteIndex === 0) {
  120. const tickend = await handleStartTick();
  121. // console.log("🚀 ~ tickend:", tickend)
  122. // 节拍器返回false, 取消播放
  123. if (!tickend) {
  124. followData.isBeginMask = false
  125. followData.start = false;
  126. followData.practiceStart = false;
  127. return false;
  128. }
  129. }
  130. onClear();
  131. followData.isBeginMask = false
  132. followData.start = true;
  133. followData.practiceStart = true;
  134. // followData.index = 0;
  135. followData.index = state.activeNoteIndex;
  136. followData.list = [];
  137. initSetPlayRate();
  138. // resetPlaybackToStart();
  139. openToggleRecord(true);
  140. getNoteIndex();
  141. const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
  142. metronomeData.totalNumerator = duration.numerator || 2
  143. metronomeData.followAudioIndex = 1
  144. state.beatStartTime = 0
  145. followBeatPaly();
  146. }
  147. };
  148. /** 结束跟练 */
  149. export const handleFollowEnd = () => {
  150. onClear();
  151. followData.start = false;
  152. followData.practiceStart = false;
  153. openToggleRecord(false);
  154. followData.index = 0;
  155. console.log("结束");
  156. };
  157. // 清除当前音符右侧的音符的颜色状态
  158. const clearRightNoteColor = () => {
  159. const noteId = state.times[state.activeNoteIndex]?.id;
  160. const leftVal = document.getElementById(`vf-${noteId}`)?.getBoundingClientRect()?.left || 0;
  161. state.times.forEach((item: any) => {
  162. const note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  163. if (note?.getBoundingClientRect()?.left >= leftVal) {
  164. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  165. }
  166. });
  167. }
  168. /**
  169. * 2024.6.17 新增自动结束跟练模式功能
  170. * 如果跟练模式,唱完了最后一个有频率的音符,需要自动结束掉跟练模式
  171. * 需要判断当前音符的后面是否都是休止音符(休止音符的频率都是-1),或者是否是最后一个音符了
  172. */
  173. const autoEndFollow = () => {
  174. if (followData.index >= state.times.length) {
  175. handleFollowEnd()
  176. return
  177. }
  178. let nextIndex = followData.index + 1;
  179. const rightTimes = state.times.slice(followData.index,state.times.length)
  180. // 后面的音符是否都是休止音符
  181. const isAllRest = !rightTimes.some((item: any) => item.frequency > 1);
  182. if (isAllRest && state.times[followData.index].frequency < 1) {
  183. handleFollowEnd()
  184. return
  185. }
  186. clearRightNoteColor();
  187. }
  188. // 下一个
  189. const next = () => {
  190. if (followData.index < state.times.length) {
  191. gotoNext(state.times[followData.index]);
  192. }
  193. autoEndFollow();
  194. };
  195. // 获取当前音符
  196. const getNoteIndex = (): any => {
  197. const item = state.times[followData.index];
  198. if (item.frequency <= 0) {
  199. followData.index = followData.index + 1;
  200. next();
  201. return getNoteIndex();
  202. }
  203. noteFrequency.value = item.frequency;
  204. // state.fixedKey = item.realKey;
  205. return {
  206. id: item.id,
  207. min: item.frequency - (item.frequency - item.prevFrequency) * 0.5,
  208. max: item.frequency + (item.nextFrequency - item.frequency) * 0.5,
  209. duration: item.duration,
  210. baseFrequency: item.frequency,
  211. };
  212. };
  213. let checking = false;
  214. /** 录音回调 */
  215. const onFollowTime = (evt?: IPostMessage) => {
  216. const frequency: number = evt?.content?.frequency;
  217. // 没有开始, 不处理
  218. if (!followData.start) return;
  219. // console.log('频率', frequency)
  220. if (frequency > 0) {
  221. audioFrequency.value = frequency;
  222. // data.list.push(frequency)
  223. checked();
  224. }
  225. };
  226. let startTime = 0;
  227. const checked = () => {
  228. if (checking) return;
  229. checking = true;
  230. const item = getNoteIndex();
  231. // 降噪处理, 频率低于 当前音的50% 时, 不处理
  232. if (audioFrequency.value < item.baseFrequency * 0.5) {
  233. checking = false;
  234. return;
  235. }
  236. if (audioFrequency.value >= item.min && audioFrequency.value <= item.max) {
  237. if (startTime === 0) {
  238. startTime = Date.now();
  239. } else {
  240. const playTime = (Date.now() - startTime) / 1000;
  241. // console.log('时长', playTime, item.duration / 2)
  242. if (playTime >= item.duration * 0.6) {
  243. startTime = 0;
  244. followData.index = followData.index + 1;
  245. setColor(item, "", true);
  246. setTimeout(() => {
  247. next();
  248. checking = false;
  249. }, 3000);
  250. return;
  251. }
  252. }
  253. // console.log("频率对了", item.min, audioFrequency.value, item.max, item.duration);
  254. }
  255. // console.log("频率不对", item.min, audioFrequency.value, item.max, item.baseFrequency);
  256. setColor(item, audioFrequency.value > item.baseFrequency ? "follow-up" : "follow-down");
  257. checking = false;
  258. };
  259. const setColor = (item: any, state: "follow-up" | "follow-down" | "", isRight = false) => {
  260. const note: HTMLElement = document.querySelector(`div[data-vf=vf${item.id}]`)!;
  261. if (note) {
  262. note.classList.remove("follow-up", "follow-down", "follow-error", "follow-success");
  263. if (isRight) {
  264. note.classList.add("follow-success");
  265. } else {
  266. note.classList.add("follow-error", state);
  267. }
  268. }
  269. const _note: HTMLElement = document.getElementById(`vf-${item.id}`)!;
  270. if (_note) {
  271. const stemEl = document.getElementById(`vf-${item.id}-stem`)
  272. _note.classList.remove("follow-up", "follow-down");
  273. stemEl?.classList.remove("follow-up", "follow-down","follow-success");
  274. if (state) {
  275. _note.classList.add(state);
  276. stemEl?.classList.add(state)
  277. }
  278. if (isRight) {
  279. _note.classList.add("follow-success");
  280. stemEl?.classList.add("follow-success")
  281. }
  282. }
  283. };
  284. // 进度跟练,点击某个音符开始跟练
  285. export const skipNotePractice = () => {
  286. followData.index = state.activeNoteIndex
  287. // 清除其它音符的错误提示
  288. const noteFollows: HTMLElement[] = Array.from(document.querySelectorAll(".follow-error"));
  289. noteFollows.forEach((noteFollow) => {
  290. noteFollow?.classList.remove("follow-up", "follow-down", "follow-error");
  291. })
  292. clearRightNoteColor();
  293. }
  294. // 移动到对应音符的位置
  295. watch(
  296. () => followData.index,
  297. () => {
  298. skipNotePlay(followData.index);
  299. }
  300. );
  301. export default defineComponent({
  302. name: "follow",
  303. setup() {
  304. onMounted(async () => {
  305. /** 如果是PC端 */
  306. if (!storeData.isApp) {
  307. const canRecorder = await audioRecorder.checkSupport();
  308. if (canRecorder) {
  309. audioRecorder.init();
  310. audioRecorder.progress = (frequency: number) => {
  311. onFollowTime({ api: "", content: { frequency } });
  312. };
  313. } else {
  314. followData.earphone = true;
  315. }
  316. } else {
  317. api_cloudFollowTime(onFollowTime);
  318. }
  319. console.log("进入跟练模式");
  320. });
  321. onUnmounted(() => {
  322. // api_cloudFollowTime(onFollowTime, false);
  323. resetPlaybackToStart();
  324. onClear();
  325. // 开启了麦克风授权,才需要调用结束收音
  326. if (storeData.isApp && !followData.dontAccredit) {
  327. openToggleRecord(false);
  328. }
  329. console.log("退出跟练模式");
  330. });
  331. return () => <div></div>;
  332. },
  333. });