use-app.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import { onBeforeUnmount, onMounted, Ref, ref, watch } from 'vue'
  2. import { useClientType, useOriginSearch } from '.'
  3. import request from '/src/helpers/request'
  4. import originRequest from 'umi-request'
  5. import store from 'store'
  6. import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
  7. import detailState, { GradualTimes, isRhythmicExercises } from '/src/pages/detail/state'
  8. import SettingState from '/src/pages/detail/setting-state'
  9. import { listenerMessage, postMessage } from '/src/helpers/native-message'
  10. import audiosInstance from '/src/helpers/multiple-audio'
  11. import { formatXML, onlyVisible, getCustomInfo } from '/src/pages/detail/helpers'
  12. import { MusicSheelDetail, ShaeetStatusType } from '../index.d'
  13. import { browser, getRequestHostname, isEncoded, setGlobalData } from '/src/helpers/utils'
  14. import formatId, { formatdata, getSubjectIdCode } from '../fingering/format-id'
  15. import { evaluatStopPlay } from '../buttons/evaluating'
  16. import state from '/src/pages/detail/state'
  17. import { getGradualLengthByXml } from '/src/pages/detail/calcSpeed'
  18. import { musicInfo } from '../state'
  19. import { getInstrumentName } from '../helpers/instruments'
  20. const search = useOriginSearch()
  21. const skpList = ['Ukulele']
  22. /**
  23. * 特殊教材分类id
  24. */
  25. export const classids = [1, 2, 6, 7, 8, 9, 3, 10, 11, 12, 13, 4, 14, 15, 16, 17, 30, 31, 35, 36, 108]; // 大雅金唐, 竖笛教程, 声部训练展开的分类ID
  26. // export const classids = [1, 30, 97]; // [大雅金唐, 竖笛教程, 声部训练]
  27. /**
  28. * 大雅金唐类目
  29. */
  30. const daYaClassids = [1, 2, 6, 7, 8, 9, 3, 10, 11, 12, 13, 4, 14, 15, 16, 17]
  31. /**
  32. * 获取xml并前置格式化
  33. * @param url xml地址
  34. * @param detail 音乐详情
  35. * @returns Ref<string>
  36. */
  37. export const useXml = async (url: string, detail: MusicSheelDetail) => {
  38. const partIndex = Number(search['part-index']) || 0
  39. let score = ref<string>('')
  40. try {
  41. const xml = await originRequest(url)
  42. const parseXmlInfo = getCustomInfo(xml)
  43. if (skpList.includes(parseXmlInfo.code)) {
  44. score.value = xml
  45. } else {
  46. score.value = formatXML(parseXmlInfo.parsedXML, {
  47. title: detail.musicSheetName,
  48. })
  49. // 多种乐器分轨合并显示
  50. if (state.isCombineRender) {
  51. const customNoduleInfo = JSON.parse(localStorage.getItem('customNoduleInfo')) || []
  52. const matchMusic = customNoduleInfo.find((n: any) => n.id === id)
  53. const xjNum = matchMusic ? matchMusic.customNum : 4
  54. setGlobalData('wrapNum', xjNum)
  55. } else {
  56. score.value = onlyVisible(score.value, partIndex)
  57. }
  58. state.partIndex = partIndex
  59. }
  60. state.gradual = getGradualLengthByXml(xml)
  61. } catch (error) {}
  62. return score
  63. }
  64. /**
  65. * 设置音频信息
  66. * @param detail 音乐详情
  67. */
  68. export const useMp3s = async (detail: MusicSheelDetail) => {
  69. const search = useOriginSearch()
  70. const partIndex = ((search['part-index'] as string) || 0) as unknown as number
  71. const activebg = detail.background?.[partIndex]
  72. Object.assign(musicInfo, activebg)
  73. if (musicInfo.musicSvg) {
  74. try {
  75. musicInfo.musicSvg = typeof musicInfo.musicSvg === 'string' && musicInfo.musicSvg ? JSON.parse(musicInfo.musicSvg) : ''
  76. } catch (error) {}
  77. }
  78. // 伴奏
  79. const backgroundSong = isEncoded(detail.metronomeUrl || '') ? detail.metronomeUrl || '' : encodeURI(detail.metronomeUrl || '')
  80. // 原音
  81. const musicSong = isEncoded(activebg?.audioFileUrl|| '') ? activebg?.audioFileUrl || '' : encodeURI(activebg?.audioFileUrl|| '')
  82. console.log('伴奏:',backgroundSong,'原音:',musicSong)
  83. // 兼容未修改之前
  84. runtime.songs = {
  85. background: backgroundSong ? backgroundSong + '?t=background' : '',
  86. music: musicSong ? musicSong + '?t=music' : '',
  87. }
  88. detailState.isAppPlay = detail.audioType === 'MIDI'
  89. let defaultExtConfigJson = {
  90. skipTick: false,
  91. repeatedBeats: false,
  92. scoreSize: 'middle',
  93. }
  94. let extConfigJson = {}
  95. detailState.activeDetail = {
  96. ...detail,
  97. examSongId: detail.id,
  98. originalSpeed: 90,
  99. isAppPlay: detail.audioType === 'MIDI',
  100. extConfigJson: {
  101. ...defaultExtConfigJson,
  102. },
  103. }
  104. detailState.isPercussion = musicInfo.musicSubject == '1' || isRhythmicExercises();
  105. try {
  106. extConfigJson = JSON.parse(detail?.extConfigJson || '')
  107. } catch (error) {}
  108. detailState.activeDetail.extConfigJson = {
  109. ...detailState.activeDetail.extConfigJson,
  110. ...extConfigJson,
  111. }
  112. const setZoom = detailState.activeDetail.extConfigJson.scoreSize
  113. const zooms = store.get('zooms') || {}
  114. if (setZoom && !zooms['' + detail.id]) {
  115. store.set('zooms', { ...zooms, ['' + detail.id]: setZoom })
  116. SettingState.sett.scoreSize = setZoom
  117. }
  118. detailState.needTick = (detail.audioType === 'MP3' && detail.mp3Type === 'MP3' && detail.musicSheetType != 'CONCERT' ) || detail.audioType === 'MIDI'
  119. detailState.skipTick = detailState.activeDetail.extConfigJson.skipTick
  120. detailState.repeatedBeats = detailState.activeDetail.extConfigJson.repeatedBeats
  121. if (!runtime.songs['music']) {
  122. RuntimeUtils.changeMode('background')
  123. }
  124. // console.log({ ...detailState.activeDetail })
  125. if (!runtime.audiosInstance) {
  126. runtime.audiosInstance = new audiosInstance(Object.values(runtime.songs) as string[])
  127. }
  128. }
  129. /**
  130. * 获取异形屏信息
  131. * @returns {Promise<void>}
  132. */
  133. export const useSpecialShapedScreen = () => {
  134. const heightRef = ref<number>(0)
  135. postMessage(
  136. {
  137. api: 'isSpecialShapedScreen',
  138. },
  139. (evt) => {
  140. const height = evt?.content.notchHeight
  141. detailState.notchHeight =
  142. (browser().ios ? height * 2 : height) || (evt?.content.isSpecialShapedScreen && browser().ios ? 100 : 0)
  143. heightRef.value = detailState.notchHeight
  144. detailState.isSpecialShapedScreen = evt?.content.isSpecialShapedScreen
  145. document.documentElement.style.setProperty('--popup-loading', detailState.notchHeight / 4 + 'px')
  146. }
  147. )
  148. return [heightRef]
  149. }
  150. /**
  151. * 获取当前曲目信息
  152. * @param id 歌曲id
  153. */
  154. export const useDetail = (id: number | string): [Ref<ShaeetStatusType>, Ref<MusicSheelDetail>] => {
  155. const prefix = getRequestHostname()
  156. const status = ref<ShaeetStatusType>('loading')
  157. const data = ref<MusicSheelDetail>({})
  158. status.value = 'loading'
  159. request
  160. .get(`/musicSheet/detail/${id}`, {
  161. prefix: prefix,
  162. })
  163. .then((res) => {
  164. useMp3s(res.data)
  165. data.value = {
  166. ...res.data,
  167. code:
  168. Array.isArray(res?.data?.background) && res.data.background.length
  169. ? getSubjectIdCode(res.data.background[0].musicSubject)
  170. : '',
  171. }
  172. // notation: 是能转简谱 0: 不可以,需要设置成五线谱模式, 是否是切换简谱
  173. if (data.value.notation == 0 || !sessionStorage.getItem('notation')) {
  174. SettingState.sett.type = 'staff'
  175. }
  176. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  177. detailState.isSpecialBookCategory = !classids.includes(res.data.musicSheetCategoriesId)
  178. // 大雅金唐类目,#9248 优化
  179. detailState.isDaYaCategory = daYaClassids.includes(res.data.musicSheetCategoriesId)
  180. if (detailState.isDaYaCategory) {
  181. ;(window as any).customSectionAmount = SettingState.sett.openCustomNodule
  182. const customNoduleInfo = JSON.parse(localStorage.getItem('customNoduleInfo')) || []
  183. const matchMusic = customNoduleInfo.find((n: any) => n.id === id)
  184. const xjNum = matchMusic ? matchMusic.customNum : 4
  185. setGlobalData('wrapNum', xjNum)
  186. }
  187. detailState.subjectId = Number(musicInfo.musicSubject)
  188. // 打击乐声部下的曲目,需要合并展示所有分轨
  189. if (Number(res.data.musicSubject) === 1 && res.data.background?.length > 1) {
  190. state.isCombineRender = true
  191. // 开启自定义每行显示的小节数
  192. ;(window as any).customSectionAmount = true
  193. setGlobalData('multitrack', res.data.background?.length)
  194. }
  195. ;(window as any).DYSubjectId = formatId(data.value.code as any)
  196. /**
  197. * 长笛教程2-5-2,符杆全部朝下
  198. * DYMusicalOrientation,0:朝上;1:朝下
  199. */
  200. if (id == 904) {
  201. ;(window as any).DYMusicalOrientation = 1
  202. }
  203. if (id == 829) {
  204. ;(window as any).DYMusicalOrientation = 0
  205. }
  206. status.value = 'success'
  207. // 额外配置
  208. let extConfigJson = {
  209. gradualTimes: {},
  210. }
  211. try {
  212. if (data.value?.extConfigJson) {
  213. extConfigJson = {
  214. ...extConfigJson,
  215. ...JSON.parse(data.value.extConfigJson),
  216. }
  217. }
  218. } catch (error) {}
  219. state.gradualTimes = extConfigJson.gradualTimes as GradualTimes
  220. // 合奏设置
  221. if (res?.data?.musicSheetType == 'CONCERT') {
  222. const backgrounds = res?.data?.background || [];
  223. const partIndex = Number(search['part-index']) || 0
  224. let track = backgrounds[partIndex]?.track
  225. if (backgrounds[0]?.track?.toLocaleUpperCase() == 'COMMON'){
  226. track = backgrounds[partIndex + 1]?.track
  227. }
  228. const instrumentName = getInstrumentName(track)
  229. console.log("🚀 ~ track:", track)
  230. detailState.partName = track + (instrumentName ? `(${instrumentName})` : '')
  231. const _track = Object.keys(formatdata).filter((key) => key.includes(track) || track.includes(key))[0]
  232. data.value.code = _track
  233. }
  234. })
  235. .catch(() => (status.value = 'error'))
  236. return [status, data]
  237. }
  238. /**
  239. * 监听后台切换状态,暂停播放与评测
  240. */
  241. export const useSuspendPlay = () => {
  242. listenerMessage('suspendPlay', () => {
  243. if (detailState.activeTick > -1) {
  244. RuntimeUtils.stopTick()
  245. }
  246. console.log(runtime.playState)
  247. if (runtime.playState === 'play') {
  248. RuntimeUtils.resetPlayStatus()
  249. if (runtime.evaluatingStatus) {
  250. // postMessage(
  251. // {
  252. // api: 'pauseRecording',
  253. // },
  254. // () => {
  255. // detailState.isPauseRecording = true
  256. // }
  257. // )
  258. evaluatStopPlay()
  259. }
  260. }
  261. })
  262. }