四零语境前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2586 lines
96 KiB

1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
  1. <template>
  2. <view class="book-container">
  3. <!-- 条件编译 -->
  4. <!-- #ifndef H5 -->
  5. <uv-status-bar></uv-status-bar>
  6. <!-- 自定义顶部导航栏 -->
  7. <view class="custom-navbar" :class="{ 'navbar-hidden': !showNavbar }">
  8. <uv-status-bar></uv-status-bar>
  9. <view class="navbar-content">
  10. <view class="navbar-left" @click="goBack">
  11. <uv-icon name="arrow-left" size="20" color="#262626"></uv-icon>
  12. </view>
  13. <view class="navbar-title">{{ currentPageTitle }}</view>
  14. </view>
  15. </view>
  16. <!-- #endif -->
  17. <!-- Swiper内容区域 -->
  18. <swiper class="content-swiper" :current="currentPage - 1" @change="onSwiperChange">
  19. <swiper-item v-for="(page, index) in bookPages" :key="index" class="swiper-item">
  20. <scroll-view scroll-y :scroll-top="scrollTops[index] || 0" :scroll-with-animation="true"
  21. style="height: 100vh;" class="scroll-container" @scroll="onScroll" @touchstart="onTouchStart"
  22. @touchmove="onTouchMove" @touchend="onTouchEnd">
  23. <view class="content-area" @click="toggleNavbar">
  24. <view class="title">{{ currentPageTitle }}</view>
  25. <!-- 会员限制页面 -->
  26. <view v-if="!isMember && pagePay[index] === 'Y' && userInfo.freeUser != 'Y'" class="member-content">
  27. <text class="member-title">{{ pageTitles[index] }}</text>
  28. <view class="member-button" @click.stop="unlockBook">
  29. <text class="member-button-text">升级会员解锁</text>
  30. </view>
  31. </view>
  32. <!-- 图片卡片页面 -->
  33. <view class="card-content" v-else-if="pageTypes[index] === '1'">
  34. <view class="card-line">
  35. <image :src="configParamContent('highlight_icon')" class="card-line-image"
  36. mode="aspectFill" />
  37. <text class="card-line-text">划线重点</text>
  38. </view>
  39. <view v-for="(item, itemIndex) in page" :key="itemIndex" class="text-content">
  40. <image class="card-image" v-if="item && item.type === 'image'" :src="item.imageUrl"
  41. mode="widthFix"></image>
  42. <!-- <view :class="['english-text-container', 'clickable-text', { 'lead-text': isCardTextHighlighted(page, itemIndex) }]" v-else-if="item && item.type === 'text' && item.language === 'en' && item.content" @click.stop="handleTextClick(item.content, item, index)" >
  43. <text
  44. v-for="(token, tokenIndex) in splitEnglishSentence(item.content)"
  45. :key="tokenIndex"
  46. :class="['english-token', { 'clickable-word': token.isWord && findWordDefinition(token.text) }]"
  47. @click.stop="token.isWord && findWordDefinition(token.text) ? handleWordClick(token.text) : null"
  48. user-select
  49. :style="item.style"
  50. >{{ token.text }}</text>
  51. </view> -->
  52. <!-- <view :class="{ 'lead-text': isCardTextHighlighted(page, itemIndex) }" v-else-if="item && item.type === 'text' && item.language === 'zh' && item.content" @click.stop="handleTextClick(item.content, item, index)"> -->
  53. <view :class="{
  54. 'lead-text': isCardTextHighlighted(page, itemIndex),
  55. 'introduction-text' : item.isLead,
  56. }"
  57. v-else-if="item && item.type === 'text' && item.content"
  58. @click.stop="handleTextClick(item.content, item, index)">
  59. <text v-for="(segment, segmentIndex) in processChineseText(item.content)"
  60. :key="segmentIndex"
  61. :class="['chinese-segment', { 'clickable-keyword': segment.isKeyword }]"
  62. @click.stop="segment.isKeyword ? handleChineseKeywordClick(segment.keywordData) : handleTextClick(item.content, item, index)"
  63. user-select :style="item.style" :id="`text-segment-${segmentIndex}`">{{
  64. segment.text }}</text>
  65. </view>
  66. </view>
  67. </view>
  68. <view v-else>
  69. <view v-for="(item, itemIndex) in page" :key="itemIndex">
  70. <!-- 文本页面 -->
  71. <view v-if="item && item.type === 'text' && item.content" class="text-content">
  72. <view :class="{
  73. 'lead-text': isTextHighlighted(page, itemIndex),
  74. 'introduction-text' : item.isLead,
  75. }"
  76. @click.stop="handleTextClick(item.content, item, index)"
  77. :ref="`textRef_${index}_${itemIndex}`" :id="`text-${itemIndex}`">
  78. <text class="content-text clickable-text"
  79. :style="item.style" user-select>
  80. {{ item.content }}
  81. </text>
  82. </view>
  83. </view>
  84. <!-- 图片页面 -->
  85. <view v-else-if="item.type === 'image'" class="image-container"
  86. :ref="`imageRef_${index}_${itemIndex}`">
  87. <image class="content-image" :src="item.imageUrl" mode="widthFix"></image>
  88. </view>
  89. <!-- 视频页面 -->
  90. <view v-else-if="item.type === 'video'" class="video-content" @click.stop>
  91. <!-- 视频加载状态 -->
  92. <view v-if="videoLoading" class="video-loading">
  93. <text class="loading-text">视频加载中...</text>
  94. </view>
  95. <!-- 视频播放器 -->
  96. <video v-else :src="item.url" class="video-player" controls :poster="item.coverUrl"
  97. @loadstart="onVideoLoadStart" @loadeddata="onVideoLoadStart"
  98. @error="onVideoError"></video>
  99. </view>
  100. </view>
  101. </view>
  102. </view>
  103. </scroll-view>
  104. </swiper-item>
  105. </swiper>
  106. <!-- 自定义底部控制栏 -->
  107. <CustomTabbar :show-navbar="showNavbar" :current-page="currentPage" :course-id="courseId" :voice-id="voiceId"
  108. :book-pages="bookPages" :is-text-page="isTextPage" :should-load-audio="shouldLoadAudio"
  109. :is-member="isMember" :current-page-requires-member="currentPageRequiresMember" :page-pay="pagePay"
  110. :is-word-audio-playing="isWordAudioPlaying" @toggle-course-popup="toggleCoursePopup"
  111. @toggle-sound="toggleSound" @go-to-page="goToPage" @previous-page="previousPage" @next-page="nextPage"
  112. @audio-state-change="onAudioStateChange" @highlight-change="onHighlightChange"
  113. @scroll-to-text="onScrollToText" @voice-change-complete="onVoiceChangeComplete"
  114. @voice-change-error="onVoiceChangeError" @page-data-needed="onPageDataNeeded" ref="customTabbar" />
  115. <!-- 课程选择弹出窗 -->
  116. <CoursePopup :style="{ zIndex: 10000 }" :course-list="courseList" :current-course="currentCourse"
  117. :is-reversed="isReversed" @toggle-sort="toggleSort" @select-course="selectCourse" ref="coursePopup" />
  118. <!-- 释义弹出窗 -->
  119. <MeaningPopup :style="{ zIndex: 10000 }" :current-word-meaning="currentWordMeaning"
  120. @close-meaning-popup="closeMeaningPopup" @repeat-word-audio="repeatWordAudio" ref="meaningPopup" />
  121. <!-- 悬浮按钮组件 -->
  122. <FloatingButtons
  123. :is-last-page="isLastPage"
  124. :has-next-course="hasNextCourse"
  125. @next-course="goToNextCourse"
  126. @back-to-start="backToStart"
  127. />
  128. </view>
  129. </template>
  130. <script>
  131. import AudioControls from './AudioControls.vue'
  132. import CustomTabbar from './components/CustomTabbar.vue'
  133. import CoursePopup from './components/CoursePopup.vue'
  134. import MeaningPopup from './components/MeaningPopup.vue'
  135. import FloatingButtons from './components/FloatingButtons.vue'
  136. import audioManager from '@/utils/audioManager.js'
  137. export default {
  138. components: {
  139. AudioControls,
  140. CustomTabbar,
  141. CoursePopup,
  142. MeaningPopup,
  143. FloatingButtons
  144. },
  145. data() {
  146. return {
  147. isMember: false,
  148. memberId: '',
  149. voiceId: null,
  150. courseId: '',
  151. showNavbar: true,
  152. currentPage: 1, // 当前页面索引
  153. currentCourse: 1, // 当前课程索引
  154. currentWordMeaning: null, // 当前显示的单词释义
  155. isReversed: false, // 是否倒序显示
  156. // 文本高亮相关 - 由AudioControls组件管理,这里只保留必要的接口
  157. currentHighlightIndex: -1, // 当前高亮的文本索引,用于模板渲染
  158. wordAudioCache: {}, // 單詞語音緩存
  159. // 注意:音频实例现在由audioManager统一管理,不再在组件中维护
  160. isWordAudioPlaying: false, // 是否有单词音频正在播放
  161. // 音频状态相关 - 这些状态现在由AudioControls组件管理
  162. // 保留这些属性用于与AudioControls组件的数据同步
  163. isAudioLoading: false, // 音频是否正在加载
  164. hasAudioData: false, // 是否有音频数据
  165. audioLoadFailed: false, // 音频加载是否失败
  166. // 视频状态相关
  167. videoLoading: false, // 视频是否正在加载
  168. // 滚动相关
  169. scrollTops: [], // 每个页面的scroll-view滚动位置数组
  170. scrollDebounceTimer: null, // 滚动防抖定时器
  171. isScrolling: false, // 是否正在滚动中
  172. // 手动滚动检测相关
  173. isUserTouching: false, // 用户是否正在触摸屏幕
  174. touchStartTime: 0, // 触摸开始时间
  175. touchStartY: 0, // 触摸开始Y坐标
  176. userScrollTimer: null, // 用户滚动检测定时器
  177. lastUserScrollTime: 0, // 最后一次用户滚动时间
  178. courseIdList: [],
  179. bookTitle: '',
  180. courseList: [
  181. ],
  182. // 二维数组 代表每个页面
  183. bookPages: [
  184. ],
  185. // 存储每个页面的标题
  186. pageTitles: [],
  187. // 存储每个页面的type信息
  188. pageTypes: [],
  189. // 存储每个页面的单词释义数据
  190. pageWords: [],
  191. // 存储每个页面的付费状态
  192. pagePay: [],
  193. }
  194. },
  195. onShow() {
  196. if (uni.getStorageSync('token')) {
  197. this.$store.dispatch('getUserInfo');
  198. }
  199. },
  200. computed: {
  201. displayCourseList() {
  202. return this.isReversed ? [...this.courseList].reverse() : this.courseList;
  203. },
  204. // 从Vuex获取音色列表
  205. voiceList() {
  206. return this.$store.state.voiceList;
  207. },
  208. // 从Vuex获取默认音色ID
  209. defaultVoiceId() {
  210. return this.$store.state.defaultVoiceId;
  211. },
  212. // 判断当前页面是否为文字类型
  213. isTextPage() {
  214. // 如果是卡片页面(type为'1'),不显示音频控制栏
  215. if (this.currentPageType === '1') {
  216. return true;
  217. }
  218. const currentPageData = this.bookPages[this.currentPage - 1];
  219. // currentPageData是一个数组 其中的一个元素的type是text就会返回true
  220. return currentPageData && currentPageData.some(item => item.type === 'text');
  221. },
  222. // 判断当前页面是否需要加载音频(包括文本页面和卡片页面)
  223. shouldLoadAudio() {
  224. // 文本页面需要加载音频
  225. if (this.isTextPage) {
  226. return true;
  227. }
  228. // 卡片页面(type为'1')也需要加载音频以支持点击播放
  229. if (this.currentPageType === '1') {
  230. return true;
  231. }
  232. return false;
  233. },
  234. // 动态页面标题
  235. currentPageTitle() {
  236. return this.pageTitles[this.currentPage - 1] || this.bookTitle;
  237. },
  238. // 当前页面类型
  239. currentPageType() {
  240. return this.pageTypes[this.currentPage - 1] || '';
  241. },
  242. // 当前页面的单词释义数据
  243. currentPageWords() {
  244. return this.pageWords[this.currentPage - 1] || [];
  245. },
  246. // 当前页面是否需要会员
  247. currentPageRequiresMember() {
  248. // 免费用户不受会员限制
  249. if (this.userInfo && this.userInfo.freeUser === 'Y') {
  250. return false;
  251. }
  252. return this.pagePay[this.currentPage - 1] === 'Y';
  253. },
  254. // 判断是否为当前课程的最后一页
  255. isLastPage() {
  256. return this.currentPage === this.bookPages.length;
  257. },
  258. // 判断是否有下一课
  259. hasNextCourse() {
  260. if (!this.courseList || this.courseList.length === 0) return false;
  261. // 使用 courseId 而不是 currentCourse,因为 courseId 是当前正在学习的课程ID
  262. const currentCourseIndex = this.courseList.findIndex(course => course.id == this.courseId);
  263. return currentCourseIndex >= 0 && currentCourseIndex < this.courseList.length - 1;
  264. }
  265. },
  266. // watch: {
  267. // scrollTops: {
  268. // handler(newVal, oldVal) {
  269. // console.log('📊 scrollTops变化:', {
  270. // currentPage: this.currentPage,
  271. // newScrollTops: newVal,
  272. // currentPageScrollTop: newVal[this.currentPage - 1]
  273. // });
  274. // },
  275. // deep: true
  276. // }
  277. // },
  278. methods: {
  279. // 触摸开始事件 - 检测用户开始触摸
  280. onTouchStart(e) {
  281. this.isUserTouching = true;
  282. this.touchStartTime = Date.now();
  283. this.touchStartY = e.touches[0].pageY;
  284. // 清除之前的用户滚动定时器
  285. if (this.userScrollTimer) {
  286. clearTimeout(this.userScrollTimer);
  287. this.userScrollTimer = null;
  288. }
  289. console.log('👆 用户开始触摸屏幕');
  290. },
  291. // 触摸移动事件 - 检测用户滚动操作
  292. onTouchMove(e) {
  293. if (!this.isUserTouching) return;
  294. const currentY = e.touches[0].pageY;
  295. const deltaY = Math.abs(currentY - this.touchStartY);
  296. // 如果移动距离超过阈值,认为是滚动操作
  297. if (deltaY > 10) {
  298. // 记录用户滚动时间
  299. this.lastUserScrollTime = Date.now();
  300. // 如果当前正在自动滚动,立即停止
  301. if (this.isScrolling) {
  302. console.log('🛑 检测到用户手动滚动,停止自动滚动');
  303. this.isScrolling = false;
  304. // 清除滚动防抖定时器
  305. if (this.scrollDebounceTimer) {
  306. clearTimeout(this.scrollDebounceTimer);
  307. this.scrollDebounceTimer = null;
  308. }
  309. }
  310. }
  311. },
  312. // 触摸结束事件 - 用户停止触摸
  313. onTouchEnd(e) {
  314. this.isUserTouching = false;
  315. // 设置一个短暂的延迟,在用户停止触摸后的一段时间内仍然阻止自动滚动
  316. // 这样可以避免用户刚停止滚动就立即触发自动滚动
  317. this.userScrollTimer = setTimeout(() => {
  318. console.log('✋ 用户滚动操作结束,允许自动滚动');
  319. this.userScrollTimer = null;
  320. }, 500); // 减少到500ms,提高响应性
  321. console.log('👆 用户停止触摸屏幕');
  322. },
  323. // 检查是否应该阻止自动滚动
  324. shouldPreventAutoScroll() {
  325. // 降低敏感度:只有在用户正在触摸且最近有滚动行为时才阻止
  326. const now = Date.now();
  327. const recentUserScroll = this.userScrollTimer !== null && (now - this.lastUserScrollTime) < 1000;
  328. return this.isUserTouching && recentUserScroll;
  329. },
  330. // 处理scroll-view滚动事件
  331. onScroll(e) {
  332. // 更新当前页面的滚动位置
  333. const scrollTop = e.detail.scrollTop;
  334. const currentPageIndex = this.currentPage - 1;
  335. const previousScrollTop = this.scrollTops[currentPageIndex] || 0;
  336. // 只有当滚动位置发生显著变化时才更新
  337. if (Math.abs(previousScrollTop - scrollTop) > 5) {
  338. // 检测是否为手动滚动(如果正在自动滚动中,但滚动位置与预期不符,则认为是手动滚动)
  339. if (this.isScrolling) {
  340. // 提高手动滚动检测阈值,减少误判
  341. const scrollDifference = Math.abs(previousScrollTop - scrollTop);
  342. if (scrollDifference > 80) { // 从50提高到80,减少误判
  343. console.log('🖐️ 检测到手动滚动,中断自动滚动状态');
  344. this.isScrolling = false;
  345. this.lastUserScrollTime = Date.now(); // 记录手动滚动时间
  346. }
  347. }
  348. this.$set(this.scrollTops, currentPageIndex, scrollTop);
  349. }
  350. },
  351. // 视频事件处理方法
  352. onVideoLoadStart() {
  353. this.videoLoading = true;
  354. },
  355. onVideoCanPlay() {
  356. this.videoLoading = false;
  357. },
  358. onVideoError() {
  359. this.videoLoading = false;
  360. uni.showToast({
  361. title: '视频加载失败',
  362. icon: 'none',
  363. duration: 2000
  364. });
  365. },
  366. // 獲取用戶會員信息 判斷是否和傳參傳過來的會員id相同
  367. async getMemberInfo() {
  368. // 检查是否为免费用户
  369. if (this.userInfo && this.userInfo.freeUser === 'Y') {
  370. this.isMember = true; // 免费用户享有会员权限
  371. return;
  372. }
  373. const memberRes = await this.$api.member.getUserMemberInfo()
  374. if (memberRes.code === 200) {
  375. this.isMember = memberRes.result.map(item => item.memberId).includes(this.memberId)
  376. }
  377. },
  378. // 处理AudioControls组件的事件
  379. onAudioStateChange(audioState) {
  380. // 更新高亮状态
  381. this.currentHighlightIndex = audioState.currentHighlightIndex;
  382. // 更新音频加载状态(用于控制UI显示)
  383. if (audioState.hasOwnProperty('isLoading')) {
  384. this.isAudioLoading = audioState.isLoading;
  385. }
  386. // 更新音频数据状态
  387. if (audioState.hasOwnProperty('hasAudioData')) {
  388. this.hasAudioData = audioState.hasAudioData;
  389. }
  390. // 更新音频加载失败状态
  391. if (audioState.hasOwnProperty('audioLoadFailed')) {
  392. this.audioLoadFailed = audioState.audioLoadFailed;
  393. }
  394. },
  395. // 处理页面数据需要重新加载的事件
  396. async onPageDataNeeded(pageNumber) {
  397. console.log('收到页面数据需要重新加载的请求,页面:', pageNumber);
  398. // 如果页面数据不存在或为空,重新获取
  399. if (!this.bookPages || this.bookPages.length === 0 || !this.bookPages[pageNumber - 1]) {
  400. console.log('页面数据不存在,重新获取页面数据');
  401. try {
  402. await this.getBookPages();
  403. console.log('页面数据重新获取完成');
  404. // 页面数据更新后,AudioControls组件的bookPages监听器会自动触发音频获取
  405. // 无需手动调用getCurrentPageAudio,避免重复调用
  406. } catch (error) {
  407. console.error('重新获取页面数据失败:', error);
  408. }
  409. } else {
  410. console.log('页面数据已存在,无需重新获取');
  411. }
  412. },
  413. // 处理音色切换完成事件
  414. onVoiceChangeComplete(data) {
  415. // 可以在这里添加一些UI反馈,比如显示切换成功的提示
  416. if (data.hasAudioData) {
  417. } else {
  418. }
  419. // 如果启用了预加载所有页面
  420. if (data.preloadAllPages) {
  421. // 可以显示一个提示,告诉用户正在后台加载
  422. uni.showToast({
  423. title: '正在加载新音色...',
  424. icon: 'loading',
  425. duration: 2000
  426. });
  427. }
  428. },
  429. // 处理音色切换错误事件
  430. onVoiceChangeError(error) {
  431. console.error('音色切换失败:', error);
  432. // 可以在这里显示错误提示给用户
  433. uni.showToast({
  434. title: '音色切换失败,请重试',
  435. icon: 'none',
  436. duration: 2000
  437. });
  438. },
  439. // 处理音频切换时的自动滚动
  440. // onScrollToText(refName) {
  441. // try {
  442. // console.log('🎯 onScrollToText 被调用:', refName);
  443. //
  444. // // 调用scrollTo插件
  445. // this.$scrollTo(refName);
  446. //
  447. // } catch (error) {
  448. // console.error('❌ onScrollToText 执行失败:', error);
  449. // }
  450. // },
  451. // 处理文本点击事件
  452. handleTextClick(textContent, item, pageIndex) {
  453. // console.log('🎯 ===== 文本点击事件开始 =====');
  454. // console.log('📝 点击文本:', textContent);
  455. // console.log('📄 textContent类型:', typeof textContent);
  456. // console.log('❓ textContent是否为undefined:', textContent === undefined);
  457. // console.log('📦 完整item对象:', item);
  458. // console.log('📝 item.content:', item ? item.content : 'item为空');
  459. // console.log('📖 当前页面索引:', this.currentPage);
  460. // console.log('👆 点击的页面索引:', pageIndex);
  461. // console.log('📊 当前页面类型:', this.currentPageType);
  462. // console.log('📄 是否为文本页面:', this.isTextPage);
  463. // console.log('📋 当前页面数据:', this.bookPages[this.currentPage - 1]);
  464. // console.log('📏 页面数据长度:', this.bookPages[this.currentPage - 1] ? this.bookPages[this.currentPage - 1].length : '页面不存在');
  465. // 检查音频播放状态
  466. // console.log('🎵 ===== 音频状态检查 =====');
  467. // console.log(' isWordAudioPlaying:', this.isWordAudioPlaying);
  468. // console.log(' currentWordAudio存在:', !!this.currentWordAudio);
  469. // console.log(' currentWordMeaning存在:', !!this.currentWordMeaning);
  470. if (this.isWordAudioPlaying) {
  471. // console.log('⚠️ 检测到单词音频正在播放状态,这可能会阻止句子音频播放');
  472. // console.log('🔄 尝试重置音频播放状态...');
  473. this.isWordAudioPlaying = false;
  474. // console.log('✅ 音频播放状态已重置');
  475. }
  476. // 检查是否点击的是当前页面
  477. if (pageIndex !== undefined && pageIndex !== this.currentPage - 1) {
  478. console.warn('⚠️ 点击的不是当前页面,忽略点击事件');
  479. // console.log(` 期望页面: ${this.currentPage - 1}, 点击页面: ${pageIndex}`);
  480. return;
  481. }
  482. // 验证参数有效性
  483. if (!item) {
  484. console.error('❌ handleTextClick: item参数为空');
  485. uni.showToast({
  486. title: '数据错误,请刷新页面',
  487. icon: 'none'
  488. });
  489. return;
  490. }
  491. // 如果textContent为undefined,尝试从item中获取
  492. if (!textContent && item && item.content) {
  493. textContent = item.content;
  494. }
  495. // 最终验证textContent
  496. if (!textContent || typeof textContent !== 'string' || textContent.trim() === '') {
  497. console.error('❌ handleTextClick: 无效的文本内容', textContent);
  498. uni.showToast({
  499. title: '文本内容无效',
  500. icon: 'none'
  501. });
  502. return;
  503. }
  504. if (!this.$refs.customTabbar) {
  505. console.error('❌ customTabbar引用不存在');
  506. uni.showToast({
  507. title: '音频控制组件未准备好',
  508. icon: 'none'
  509. });
  510. return;
  511. }
  512. // console.log(' audioControls存在:', !!this.$refs.customTabbar.$refs.audioControls);
  513. if (!this.$refs.customTabbar.$refs.audioControls) {
  514. console.error('❌ audioControls引用不存在');
  515. uni.showToast({
  516. title: '音频控制组件未准备好',
  517. icon: 'none'
  518. });
  519. return;
  520. }
  521. // 检查当前页面是否为文本页面或卡片页面
  522. // 卡片页面(type为'1')现在也支持整句音频播放
  523. // 特别针对划线重点页面的调试
  524. if (this.currentPageType === '1') {
  525. }
  526. if (!this.isTextPage && this.currentPageType !== '1') {
  527. console.warn('⚠️ 当前页面不是文本页面或卡片页面');
  528. uni.showToast({
  529. title: '当前页面不支持音频播放',
  530. icon: 'none'
  531. });
  532. return;
  533. }
  534. // 获取音频控制组件实例
  535. const audioControls = this.$refs.customTabbar.$refs.audioControls;
  536. // 检查音频是否正在加载中
  537. if (audioControls.isAudioLoading) {
  538. uni.showToast({
  539. title: '音频正在加载中,请稍后再试',
  540. icon: 'loading',
  541. duration: 1500
  542. });
  543. // 等待音频加载完成后自动播放
  544. const checkAndPlay = () => {
  545. if (!audioControls.isAudioLoading && audioControls.currentPageAudios.length > 0) {
  546. const success = audioControls.playSpecificAudio(textContent);
  547. if (!success) {
  548. console.error('❌ 音频加载完成后播放失败');
  549. }
  550. } else if (!audioControls.isAudioLoading) {
  551. console.error('❌ 音频加载完成但没有音频数据');
  552. uni.showToast({
  553. title: '当前页面没有音频内容',
  554. icon: 'none'
  555. });
  556. } else {
  557. // 继续等待
  558. setTimeout(checkAndPlay, 500);
  559. }
  560. };
  561. // 延迟检查,给音频加载一些时间
  562. setTimeout(checkAndPlay, 500);
  563. return;
  564. }
  565. // 检查是否有音频数据
  566. if (!audioControls.currentPageAudios || audioControls.currentPageAudios.length === 0) {
  567. console.warn('⚠️ 当前页面没有音频数据,尝试重新加载');
  568. uni.showToast({
  569. title: '正在重新加载音频...',
  570. icon: 'loading'
  571. });
  572. // 尝试重新加载音频
  573. audioControls.getCurrentPageAudio();
  574. // 等待重新加载完成后播放
  575. const retryPlay = () => {
  576. if (!audioControls.isAudioLoading && audioControls.currentPageAudios.length > 0) {
  577. const success = audioControls.playSpecificAudio(textContent);
  578. if (!success) {
  579. console.error('❌ 音频重新加载后播放失败');
  580. }
  581. } else if (!audioControls.isAudioLoading) {
  582. console.error('❌ 音频重新加载失败');
  583. uni.showToast({
  584. title: '音频加载失败,请检查网络连接',
  585. icon: 'none'
  586. });
  587. } else {
  588. // 继续等待
  589. setTimeout(retryPlay, 500);
  590. }
  591. };
  592. setTimeout(retryPlay, 1500);
  593. return;
  594. }
  595. // 调用AudioControls组件的播放指定音频方法
  596. const success = audioControls.playSpecificAudio(textContent);
  597. // console.log('🎵 playSpecificAudio 返回结果:', success);
  598. if (success) {
  599. // console.log('✅ 成功播放指定音频段落');
  600. } else {
  601. console.error('❌ 播放指定音频段落失败');
  602. // console.log('💡 失败可能原因:');
  603. // console.log(' 1. 文本内容与音频数据不匹配');
  604. // console.log(' 2. 音频数据尚未加载完成');
  605. // console.log(' 3. 音频文件路径错误或文件损坏');
  606. // console.log(' 4. 网络连接问题');
  607. }
  608. // console.log('🎯 ===== 文本点击事件结束 =====');
  609. },
  610. onHighlightChange(highlightData) {
  611. // 兼容旧格式(直接传递索引)和新格式(传递对象)
  612. if (typeof highlightData === 'number') {
  613. // 旧格式:直接是索引
  614. this.currentHighlightIndex = highlightData;
  615. } else if (typeof highlightData === 'object' && highlightData !== null) {
  616. // 新格式:包含详细信息的对象
  617. this.currentHighlightIndex = highlightData.highlightIndex;
  618. // 可以在这里处理分段音频的额外信息
  619. if (highlightData.isSegmented) {
  620. // console.log('分段音频高亮:', {
  621. // highlightIndex: highlightData.highlightIndex,
  622. // segmentIndex: highlightData.segmentIndex,
  623. // startIndex: highlightData.startIndex,
  624. // endIndex: highlightData.endIndex,
  625. // currentText: highlightData.currentText
  626. // });
  627. }
  628. } else {
  629. // 清除高亮
  630. this.currentHighlightIndex = -1;
  631. }
  632. },
  633. // 处理滚动到高亮文本
  634. onScrollToText(scrollData) {
  635. console.log('📍 收到滚动请求:', scrollData);
  636. // 检查是否应该阻止自动滚动(用户正在手动操作)
  637. if (this.shouldPreventAutoScroll()) {
  638. console.log('🚫 用户正在手动滚动,跳过自动滚动到文本');
  639. return;
  640. }
  641. // 防抖处理:如果正在滚动中,清除之前的定时器
  642. if (this.scrollDebounceTimer) {
  643. clearTimeout(this.scrollDebounceTimer);
  644. }
  645. this.scrollDebounceTimer = setTimeout(() => {
  646. // 再次检查是否应该阻止自动滚动
  647. if (this.shouldPreventAutoScroll()) {
  648. console.log('🚫 防抖延迟后检测到用户手动滚动,跳过自动滚动到文本');
  649. return;
  650. }
  651. this.performScrollToText(scrollData);
  652. }, 50); // 减少防抖延迟,提高响应性
  653. },
  654. // 执行滚动到高亮文本的具体逻辑
  655. performScrollToText(scrollData) {
  656. // 最终检查:如果用户正在手动操作,直接返回
  657. if (this.shouldPreventAutoScroll()) {
  658. console.log('🚫 执行滚动前检测到用户手动操作,取消自动滚动');
  659. return;
  660. }
  661. // 确保在任何情况下都能重置滚动状态
  662. const resetScrollingState = () => {
  663. this.isScrolling = false;
  664. console.log('🔄 滚动状态已重置');
  665. };
  666. // 设置安全超时,确保状态不会永久卡住
  667. const safetyTimeout = setTimeout(() => {
  668. if (this.isScrolling) {
  669. console.warn('⚠️ 滚动状态安全超时,强制重置');
  670. resetScrollingState();
  671. }
  672. }, 2000); // 2秒安全超时
  673. if (!scrollData || typeof scrollData.highlightIndex !== 'number' || scrollData.highlightIndex < 0) {
  674. console.warn('滚动数据无效:', scrollData);
  675. clearTimeout(safetyTimeout);
  676. return;
  677. }
  678. // 确保在当前页面
  679. if (scrollData.currentPage && scrollData.currentPage !== this.currentPage) {
  680. console.warn('页面不匹配,跳过滚动:', {
  681. scrollDataPage: scrollData.currentPage,
  682. currentPage: this.currentPage
  683. });
  684. clearTimeout(safetyTimeout);
  685. return;
  686. }
  687. // 如果正在滚动中,跳过本次滚动
  688. if (this.isScrolling) {
  689. console.warn('正在滚动中,跳过本次滚动');
  690. clearTimeout(safetyTimeout);
  691. return;
  692. }
  693. // 构建元素选择器
  694. let selector = '';
  695. if (scrollData.isSegmented && typeof scrollData.segmentIndex === 'number') {
  696. // 分段音频:使用分段索引
  697. selector = `#text-segment-${scrollData.segmentIndex}`;
  698. } else {
  699. // 普通音频:需要找到对应的文本元素
  700. // originalTextIndex是指向原始页面数据中的索引,需要映射到实际的DOM元素
  701. const targetItemIndex = this.findTextItemIndex(scrollData.highlightIndex);
  702. if (targetItemIndex !== -1) {
  703. selector = `#text-${targetItemIndex}`;
  704. } else {
  705. console.warn('无法找到对应的文本元素索引:', scrollData.highlightIndex);
  706. selector = `#text-${scrollData.highlightIndex}`; // 备用方案
  707. }
  708. }
  709. console.log('开始滚动到文本:', { selector, scrollData });
  710. // 标记正在滚动
  711. this.isScrolling = true;
  712. // 等待DOM更新后再查找元素
  713. this.$nextTick(async () => {
  714. try {
  715. // 获取所有元素的真实位置信息
  716. const elementPositions = await this.getAllElementPositions();
  717. console.log('📏 获取到的元素位置信息:', elementPositions);
  718. // 计算精确的滚动位置
  719. const preciseScrollTop = await this.calculatePreciseScrollPosition(scrollData, elementPositions);
  720. if (preciseScrollTop !== null) {
  721. // 检查是否需要滚动(避免不必要的滚动)
  722. const currentScroll = this.scrollTops[this.currentPage - 1] || 0;
  723. const scrollDifference = Math.abs(preciseScrollTop - currentScroll);
  724. // 提高滚动阈值,减少不必要的微小滚动
  725. if (scrollDifference > 30) { // 从20提高到30
  726. this.$set(this.scrollTops, this.currentPage - 1, preciseScrollTop);
  727. console.log('✅ 使用精确位置滚动:', {
  728. selector,
  729. preciseScrollTop,
  730. currentPage: this.currentPage,
  731. scrollDifference
  732. });
  733. // 滚动完成后重置状态
  734. setTimeout(() => {
  735. resetScrollingState();
  736. }, 200);
  737. } else {
  738. resetScrollingState();
  739. console.log('📍 目标已在最佳可视位置,无需滚动');
  740. }
  741. } else {
  742. // 精确计算失败,使用原有的查询方法作为备用
  743. console.log('🔄 精确计算失败,使用备用查询方法');
  744. this.fallbackScrollToText(selector, resetScrollingState, safetyTimeout);
  745. }
  746. } catch (error) {
  747. console.error('❌ 精确滚动计算失败:', error);
  748. // 使用原有的查询方法作为备用
  749. this.fallbackScrollToText(selector, resetScrollingState, safetyTimeout);
  750. }
  751. });
  752. },
  753. // 备用滚动方法(原有的查询方式)
  754. fallbackScrollToText(selector, resetScrollingState, safetyTimeout) {
  755. // 使用uni.createSelectorQuery获取元素位置
  756. const query = uni.createSelectorQuery().in(this);
  757. // 获取scroll-view容器的位置信息
  758. query.select('.scroll-container').boundingClientRect();
  759. // 获取目标元素的位置信息
  760. query.select(selector).boundingClientRect();
  761. query.exec((res) => {
  762. // 清除安全超时
  763. clearTimeout(safetyTimeout);
  764. const scrollViewRect = res[0];
  765. const targetRect = res[1];
  766. console.log('查询结果:', {
  767. scrollViewRect: scrollViewRect ? '找到' : '未找到',
  768. targetRect: targetRect ? '找到' : '未找到',
  769. selector
  770. });
  771. if (scrollViewRect && targetRect) {
  772. // 计算目标元素相对于scroll-view的位置
  773. const currentScrollTop = this.scrollTops[this.currentPage - 1] || 0;
  774. const targetOffsetTop = targetRect.top - scrollViewRect.top + currentScrollTop;
  775. // 计算滚动位置,让目标元素在屏幕上方1/4处(更好的阅读体验)
  776. const screenHeight = uni.getSystemInfoSync().windowHeight;
  777. const targetScrollTop = targetOffsetTop - screenHeight / 4;
  778. // 更新scroll-view的滚动位置
  779. const finalScrollTop = Math.max(0, targetScrollTop);
  780. // 检查是否需要滚动(避免不必要的滚动)
  781. const currentScroll = this.scrollTops[this.currentPage - 1] || 0;
  782. const scrollDifference = Math.abs(finalScrollTop - currentScroll);
  783. // 提高滚动阈值,减少不必要的微小滚动
  784. if (scrollDifference > 30) { // 从20提高到30,与精确滚动保持一致
  785. this.$set(this.scrollTops, this.currentPage - 1, finalScrollTop);
  786. // 滚动完成后重置状态
  787. setTimeout(() => {
  788. resetScrollingState();
  789. }, 200); // 减少等待时间
  790. console.log('✅ 滚动到高亮文本:', {
  791. selector,
  792. targetOffsetTop,
  793. finalScrollTop,
  794. currentPage: this.currentPage,
  795. scrollDifference
  796. });
  797. } else {
  798. // 不需要滚动,立即重置状态
  799. resetScrollingState();
  800. console.log('📍 目标已在最佳可视位置,无需滚动');
  801. }
  802. } else {
  803. console.error('❌ 未找到目标元素或scroll-view:', {
  804. selector,
  805. scrollViewFound: !!scrollViewRect,
  806. targetFound: !!targetRect,
  807. currentPage: this.currentPage,
  808. highlightIndex: scrollData.highlightIndex
  809. });
  810. // 尝试备用方案:直接滚动到页面顶部附近
  811. if (!targetRect) {
  812. console.log('🔄 尝试备用滚动方案');
  813. // 改进备用方案:基于highlightIndex计算更准确的位置
  814. const estimatedPosition = this.calculateEstimatedScrollPosition(scrollData.highlightIndex);
  815. this.$set(this.scrollTops, this.currentPage - 1, estimatedPosition);
  816. setTimeout(() => {
  817. resetScrollingState();
  818. }, 200);
  819. } else {
  820. // 立即重置状态
  821. resetScrollingState();
  822. }
  823. }
  824. });
  825. },
  826. // 查找文本元素在页面中的实际索引
  827. findTextItemIndex(originalTextIndex) {
  828. const currentPageData = this.bookPages[this.currentPage - 1];
  829. if (!currentPageData || !Array.isArray(currentPageData)) {
  830. return -1;
  831. }
  832. let textCount = 0;
  833. for (let i = 0; i < currentPageData.length; i++) {
  834. const item = currentPageData[i];
  835. if (item && item.type === 'text' && item.content) {
  836. if (textCount === originalTextIndex) {
  837. return i; // 返回在页面数组中的实际索引
  838. }
  839. textCount++;
  840. }
  841. }
  842. return -1; // 未找到
  843. },
  844. // 获取所有页面元素的位置信息
  845. async getAllElementPositions() {
  846. return new Promise((resolve) => {
  847. const currentPageData = this.bookPages[this.currentPage - 1];
  848. if (!currentPageData || !Array.isArray(currentPageData)) {
  849. resolve([]);
  850. return;
  851. }
  852. const query = uni.createSelectorQuery().in(this);
  853. const elementPositions = [];
  854. // 获取scroll-container的位置作为基准
  855. query.select('.scroll-container').boundingClientRect();
  856. // 为每个元素添加查询
  857. currentPageData.forEach((item, index) => {
  858. if (item && (item.type === 'text' || item.type === 'image' || item.type === 'video')) {
  859. if (item.type === 'text') {
  860. query.select(`#text-${index}`).boundingClientRect();
  861. } else if (item.type === 'image') {
  862. query.select(`.image-container`).boundingClientRect();
  863. } else if (item.type === 'video') {
  864. query.select(`.video-content`).boundingClientRect();
  865. }
  866. }
  867. });
  868. query.exec((res) => {
  869. const containerRect = res[0];
  870. if (!containerRect) {
  871. resolve([]);
  872. return;
  873. }
  874. // 处理查询结果
  875. let resultIndex = 1; // 跳过第一个容器结果
  876. currentPageData.forEach((item, index) => {
  877. if (item && (item.type === 'text' || item.type === 'image' || item.type === 'video')) {
  878. const elementRect = res[resultIndex];
  879. if (elementRect) {
  880. elementPositions.push({
  881. index: index,
  882. type: item.type,
  883. top: elementRect.top - containerRect.top,
  884. height: elementRect.height,
  885. bottom: elementRect.top - containerRect.top + elementRect.height
  886. });
  887. }
  888. resultIndex++;
  889. }
  890. });
  891. resolve(elementPositions);
  892. });
  893. });
  894. },
  895. // 检查元素是否在可视范围内
  896. isElementInViewport(elementPosition, currentScrollTop) {
  897. const screenHeight = uni.getSystemInfoSync().windowHeight;
  898. const viewportTop = currentScrollTop;
  899. const viewportBottom = currentScrollTop + screenHeight;
  900. // 元素的顶部和底部位置
  901. const elementTop = elementPosition.top;
  902. const elementBottom = elementPosition.bottom;
  903. // 检查元素是否完全或部分在可视范围内
  904. const isVisible = elementBottom > viewportTop && elementTop < viewportBottom;
  905. // 计算元素在可视范围内的比例
  906. const visibleTop = Math.max(elementTop, viewportTop);
  907. const visibleBottom = Math.min(elementBottom, viewportBottom);
  908. const visibleHeight = Math.max(0, visibleBottom - visibleTop);
  909. const visibilityRatio = visibleHeight / elementPosition.height;
  910. return {
  911. isVisible,
  912. visibilityRatio,
  913. elementTop,
  914. elementBottom,
  915. viewportTop,
  916. viewportBottom
  917. };
  918. },
  919. // 计算最佳滚动位置
  920. calculateOptimalScrollPosition(targetElement, currentScrollTop) {
  921. const screenHeight = uni.getSystemInfoSync().windowHeight;
  922. // 检查当前元素的可见性
  923. const visibility = this.isElementInViewport(targetElement, currentScrollTop);
  924. // 如果元素已经完全可见且在合适位置,不需要滚动
  925. if (visibility.isVisible && visibility.visibilityRatio > 0.8) {
  926. // 检查元素是否在屏幕的合适位置(上方1/3到2/3之间)
  927. const elementCenter = (targetElement.top + targetElement.bottom) / 2;
  928. const relativePosition = (elementCenter - currentScrollTop) / screenHeight;
  929. if (relativePosition >= 0.2 && relativePosition <= 0.7) {
  930. console.log('📍 元素已在最佳可视位置,无需滚动');
  931. return null; // 不需要滚动
  932. }
  933. }
  934. // 计算目标滚动位置:让元素显示在屏幕上方1/3处(更舒适的阅读位置)
  935. const optimalOffsetRatio = 0.3; // 30%的位置,比1/4更舒适
  936. const offsetFromTop = screenHeight * optimalOffsetRatio;
  937. // 考虑元素高度,确保不会被截断
  938. const elementHeight = targetElement.height;
  939. const adjustedOffset = Math.min(offsetFromTop, screenHeight * 0.1); // 最小10%偏移
  940. const targetScrollTop = Math.max(0, targetElement.top - adjustedOffset);
  941. console.log('🎯 计算最佳滚动位置:', {
  942. currentVisibility: visibility,
  943. elementHeight,
  944. optimalOffsetRatio,
  945. adjustedOffset,
  946. targetScrollTop
  947. });
  948. return targetScrollTop;
  949. },
  950. // 计算精确的滚动位置
  951. async calculatePreciseScrollPosition(scrollData, elementPositions) {
  952. if (!elementPositions || elementPositions.length === 0) {
  953. return null;
  954. }
  955. let targetElementIndex = -1;
  956. if (scrollData.segmentIndex !== undefined) {
  957. // 分段音频情况
  958. targetElementIndex = scrollData.segmentIndex;
  959. } else if (scrollData.highlightIndex !== undefined) {
  960. // 普通音频情况,需要找到对应的文本元素
  961. targetElementIndex = this.findTextItemIndex(scrollData.highlightIndex);
  962. }
  963. if (targetElementIndex === -1) {
  964. return null;
  965. }
  966. // 查找目标元素的位置信息
  967. const targetElement = elementPositions.find(pos => pos.index === targetElementIndex && pos.type === 'text');
  968. if (!targetElement) {
  969. console.warn('未找到目标元素位置信息:', targetElementIndex);
  970. return null;
  971. }
  972. // 获取当前滚动位置
  973. const currentScrollTop = this.scrollTops[this.currentPage - 1] || 0;
  974. // 使用优化的滚动位置计算
  975. const targetScrollTop = this.calculateOptimalScrollPosition(targetElement, currentScrollTop);
  976. console.log('🎯 精确滚动位置计算:', {
  977. targetElementIndex,
  978. targetElement,
  979. currentScrollTop,
  980. targetScrollTop
  981. });
  982. return targetScrollTop;
  983. },
  984. // 计算估算的滚动位置(备用方案)
  985. calculateEstimatedScrollPosition(highlightIndex) {
  986. const currentPageData = this.bookPages[this.currentPage - 1];
  987. if (!currentPageData || !Array.isArray(currentPageData)) {
  988. return highlightIndex * 80; // 基础估算
  989. }
  990. // 基于页面内容计算更准确的位置
  991. let estimatedHeight = 0;
  992. let textCount = 0;
  993. for (let i = 0; i < currentPageData.length && textCount <= highlightIndex; i++) {
  994. const item = currentPageData[i];
  995. if (item && item.type === 'text' && item.content) {
  996. if (textCount === highlightIndex) {
  997. break;
  998. }
  999. // 根据内容长度估算高度
  1000. const contentLength = item.content.length;
  1001. estimatedHeight += Math.max(60, contentLength * 1.2); // 基础高度 + 内容长度因子
  1002. textCount++;
  1003. } else if (item && item.type === 'image') {
  1004. estimatedHeight += 200; // 图片估算高度
  1005. } else if (item && item.type === 'video') {
  1006. estimatedHeight += 300; // 视频估算高度
  1007. }
  1008. }
  1009. return Math.max(0, estimatedHeight - 100); // 留一些上边距
  1010. },
  1011. // 获取音色列表 拿第一个做默认的音色id
  1012. async getVoiceList() {
  1013. // 优先从Vuex获取音色列表
  1014. if (this.voiceList && this.voiceList.length > 0) {
  1015. console.log('从Vuex获取音色列表:', this.voiceList);
  1016. this.voiceId = this.defaultVoiceId || Number(this.voiceList[0].voiceType);
  1017. console.log('使用Vuex中的默认音色ID:', this.voiceId);
  1018. // 同步默认音色设置到audioManager
  1019. audioManager.setGlobalVoiceId(this.voiceId);
  1020. return;
  1021. }
  1022. // 如果Vuex中没有数据,则从API获取(兜底方案)
  1023. console.log('Vuex中无音色数据,从API获取...');
  1024. try {
  1025. const voiceRes = await this.$api.music.list()
  1026. if (voiceRes.code === 200) {
  1027. console.log('音色列表API返回:', voiceRes.result);
  1028. // 更新Vuex中的音色列表
  1029. this.$store.commit('setVoiceList', voiceRes.result);
  1030. this.voiceId = Number(voiceRes.result[0].voiceType)
  1031. console.log('获取默认音色ID:', this.voiceId, '类型:', typeof this.voiceId);
  1032. // 同步默认音色设置到audioManager
  1033. audioManager.setGlobalVoiceId(this.voiceId);
  1034. } else {
  1035. console.error('获取音色列表失败:', voiceRes);
  1036. }
  1037. } catch (error) {
  1038. console.error('获取音色列表异常:', error);
  1039. }
  1040. },
  1041. toggleNavbar() {
  1042. this.showNavbar = !this.showNavbar
  1043. },
  1044. goBack() {
  1045. uni.navigateBack()
  1046. },
  1047. toggleCoursePopup() {
  1048. if (this.$refs.coursePopup) {
  1049. this.$refs.coursePopup.open()
  1050. }
  1051. // console.log('123123123');
  1052. },
  1053. toggleSort() {
  1054. this.isReversed = !this.isReversed
  1055. },
  1056. selectCourse(courseId) {
  1057. this.currentCourse = courseId
  1058. this.courseId = courseId // 同时更新 courseId
  1059. // 这里可以添加切换课程的逻辑
  1060. // console.log('选择课程:', courseId)
  1061. this.getCourseList(courseId)
  1062. },
  1063. showWordMeaning() {
  1064. if (this.$refs.meaningPopup) {
  1065. this.$refs.meaningPopup.open()
  1066. }
  1067. },
  1068. closeMeaningPopup() {
  1069. this.currentWordMeaning = null;
  1070. // 重置音频播放状态,确保后续句子点击能正常播放
  1071. if (this.isWordAudioPlaying) {
  1072. this.isWordAudioPlaying = false;
  1073. // 如果有正在播放的音频,停止它
  1074. if (this.currentWordAudio) {
  1075. try {
  1076. this.currentWordAudio.pause();
  1077. this.currentWordAudio.destroy();
  1078. } catch (error) {
  1079. }
  1080. this.currentWordAudio = null;
  1081. }
  1082. }
  1083. },
  1084. // 将英文句子分割成单词数组
  1085. splitEnglishSentence(sentence) {
  1086. // 使用正则表达式分割句子,保留标点符号
  1087. const tokens = sentence.match(/\b\w+\b|[^\w\s]/g) || [];
  1088. return tokens.map((token, index) => ({
  1089. text: token,
  1090. index: index,
  1091. isWord: /\b\w+\b/.test(token), // 判断是否为单词
  1092. hasDefinition: false // 是否有释义,稍后会设置
  1093. }));
  1094. },
  1095. // 查找单词释义
  1096. findWordDefinition(word) {
  1097. const currentPageWords = this.pageWords[this.currentPage - 1] || [];
  1098. // 不区分大小写匹配
  1099. return currentPageWords.find(wordData =>
  1100. wordData.word.toLowerCase() === word.toLowerCase()
  1101. );
  1102. },
  1103. // 处理中文文本,标记重点词汇
  1104. processChineseText(text) {
  1105. const currentPageWords = this.pageWords[this.currentPage - 1] || [];
  1106. if (!text || currentPageWords.length === 0) {
  1107. return [{ text: text, isKeyword: false, keywordData: null }];
  1108. }
  1109. // 创建一个数组来存储处理后的文本片段
  1110. const segments = [];
  1111. let currentIndex = 0;
  1112. // 按照重点词汇的长度排序,优先匹配较长的词汇
  1113. const sortedWords = [...currentPageWords].sort((a, b) => b.word.length - a.word.length);
  1114. while (currentIndex < text.length) {
  1115. let matched = false;
  1116. // 尝试匹配重点词汇
  1117. for (const wordData of sortedWords) {
  1118. const keyword = wordData.word;
  1119. if (text.substr(currentIndex, keyword.length) === keyword) {
  1120. // 找到匹配的重点词汇
  1121. segments.push({
  1122. text: keyword,
  1123. isKeyword: true,
  1124. keywordData: wordData
  1125. });
  1126. currentIndex += keyword.length;
  1127. matched = true;
  1128. break;
  1129. }
  1130. }
  1131. if (!matched) {
  1132. // 没有匹配到重点词汇,添加单个字符
  1133. segments.push({
  1134. text: text[currentIndex],
  1135. isKeyword: false,
  1136. keywordData: null
  1137. });
  1138. currentIndex++;
  1139. }
  1140. }
  1141. // 合并相邻的非重点词汇片段
  1142. const mergedSegments = [];
  1143. let currentSegment = null;
  1144. for (const segment of segments) {
  1145. if (segment.isKeyword) {
  1146. // 如果当前有未完成的非重点词汇片段,先添加它
  1147. if (currentSegment) {
  1148. mergedSegments.push(currentSegment);
  1149. currentSegment = null;
  1150. }
  1151. // 添加重点词汇
  1152. mergedSegments.push(segment);
  1153. } else {
  1154. // 非重点词汇,合并到当前片段
  1155. if (currentSegment) {
  1156. currentSegment.text += segment.text;
  1157. } else {
  1158. currentSegment = { ...segment };
  1159. }
  1160. }
  1161. }
  1162. // 添加最后的非重点词汇片段
  1163. if (currentSegment) {
  1164. mergedSegments.push(currentSegment);
  1165. }
  1166. return mergedSegments;
  1167. },
  1168. // 初始化audioManager事件监听
  1169. initAudioManagerListeners() {
  1170. // 监听音频播放状态变化
  1171. audioManager.on('play', (data) => {
  1172. if (data?.audioType === 'word') {
  1173. this.isWordAudioPlaying = true;
  1174. }
  1175. });
  1176. audioManager.on('pause', (data) => {
  1177. if (data?.audioType === 'word') {
  1178. this.isWordAudioPlaying = false;
  1179. }
  1180. });
  1181. audioManager.on('ended', (data) => {
  1182. if (data?.audioType === 'word') {
  1183. this.isWordAudioPlaying = false;
  1184. }
  1185. });
  1186. audioManager.on('error', (data) => {
  1187. if (data?.audioType === 'word') {
  1188. this.isWordAudioPlaying = false;
  1189. uni.showToast({
  1190. title: '語音播放失敗',
  1191. icon: 'none'
  1192. });
  1193. }
  1194. });
  1195. },
  1196. async playWordAudio(word) {
  1197. try {
  1198. console.log('🎵 开始播放单词音频:', word);
  1199. // 🎯 使用audioManager的全局音色设置
  1200. const globalVoiceId = audioManager.getGlobalVoiceId();
  1201. const voiceIdToUse = globalVoiceId || this.voiceId;
  1202. if (!voiceIdToUse || voiceIdToUse === '' || voiceIdToUse === null || voiceIdToUse === undefined) {
  1203. console.warn('⚠️ 音色ID未设置,无法播放音频');
  1204. uni.showToast({
  1205. title: '音色未加载,请稍后重试',
  1206. icon: 'none',
  1207. duration: 2000
  1208. });
  1209. return;
  1210. }
  1211. console.log('🎵 使用音色ID:', voiceIdToUse, '播放文本:', word);
  1212. // 調用語音轉換API
  1213. const audioRes = await this.$api.music.textToVoice({
  1214. text: word,
  1215. voiceType: voiceIdToUse
  1216. });
  1217. console.log('🎵 API响应:', audioRes);
  1218. // 檢查響應並播放音頻
  1219. if (audioRes && audioRes.result && audioRes.result.url) {
  1220. console.log('✅ 获取到音频URL:', audioRes.result.url);
  1221. // 使用audioManager播放音频,应用全局语速设置
  1222. await audioManager.playAudio(audioRes.result.url, 'word', {
  1223. playbackRate: audioManager.getGlobalPlaybackRate()
  1224. });
  1225. } else {
  1226. console.error('❌ API响应无效:', audioRes);
  1227. uni.showToast({
  1228. title: '語音播放失敗',
  1229. icon: 'none'
  1230. });
  1231. }
  1232. } catch (error) {
  1233. console.error('❌ 播放单词语音异常:', error);
  1234. uni.showToast({
  1235. title: '語音播放失敗',
  1236. icon: 'none'
  1237. });
  1238. }
  1239. },
  1240. // 重複播放單詞語音(用於釋義彈窗中的揚聲器圖標)
  1241. repeatWordAudio() {
  1242. if (this.currentWordMeaning && this.currentWordMeaning.word) {
  1243. // 将单词和解释合并后播放音频
  1244. const combinedText = `${this.currentWordMeaning.word}${this.currentWordMeaning.meaning || ''}`;
  1245. this.playWordAudio(combinedText);
  1246. } else {
  1247. console.warn('沒有當前單詞可以播放');
  1248. }
  1249. },
  1250. // 处理单词点击事件
  1251. handleWordClick(word) {
  1252. const definition = this.findWordDefinition(word);
  1253. if (definition) {
  1254. this.currentWordMeaning = {
  1255. word: definition.word,
  1256. phonetic: definition.soundmark || '',
  1257. partOfSpeech: '', // 可以根据需要添加词性
  1258. meaning: definition.paraphrase || '',
  1259. knowledgeGain: definition.knowledge || '',
  1260. image: definition.image || ''
  1261. };
  1262. // 将单词和解释合并后播放音频
  1263. const combinedText = `${word}${definition.paraphrase || ''}`;
  1264. this.playWordAudio(combinedText);
  1265. this.showWordMeaning();
  1266. } else {
  1267. // 如果没有释义,只播放单词
  1268. if (word) {
  1269. this.playWordAudio(word);
  1270. } else {
  1271. }
  1272. }
  1273. },
  1274. // 处理中文重点词汇点击事件
  1275. handleChineseKeywordClick(keywordData) {
  1276. if (keywordData) {
  1277. this.currentWordMeaning = {
  1278. word: keywordData.word,
  1279. phonetic: keywordData.soundmark || '',
  1280. partOfSpeech: '', // 可以根据需要添加词性
  1281. meaning: keywordData.paraphrase || '',
  1282. knowledgeGain: keywordData.knowledge || '',
  1283. image: keywordData.image || ''
  1284. };
  1285. // 将词汇和解释合并后播放音频
  1286. const combinedText = `${keywordData.word}${keywordData.paraphrase || ''}`;
  1287. this.playWordAudio(combinedText);
  1288. this.showWordMeaning();
  1289. } else {
  1290. }
  1291. },
  1292. // 计算音频总时长
  1293. async calculateTotalDuration() {
  1294. let totalDuration = 0;
  1295. for (let i = 0; i < this.currentPageAudios.length; i++) {
  1296. const audio = this.currentPageAudios[i];
  1297. // 優先使用API返回的時長信息
  1298. if (audio.duration && audio.duration > 0) {
  1299. totalDuration += audio.duration;
  1300. continue;
  1301. }
  1302. // 如果沒有API時長信息,嘗試獲取音頻時長
  1303. try {
  1304. const duration = await this.getAudioDuration(audio.url);
  1305. audio.duration = duration;
  1306. totalDuration += duration;
  1307. } catch (error) {
  1308. console.error('获取音频时长失败:', error);
  1309. // 如果无法获取时长,根據文字長度估算(更精確的估算)
  1310. const textLength = audio.text.length;
  1311. // 假設每分鐘可以讀150-200個字符,這裡用180作為平均值
  1312. const estimatedDuration = Math.max(2, textLength / 3); // 每3個字符約1秒
  1313. audio.duration = estimatedDuration;
  1314. totalDuration += estimatedDuration;
  1315. console.log(`估算音頻時長 ${i + 1}:`, estimatedDuration, '秒 (文字長度:', textLength, ')');
  1316. }
  1317. }
  1318. this.totalTime = totalDuration;
  1319. },
  1320. // 获取音频时长
  1321. getAudioDuration(audioUrl) {
  1322. return new Promise((resolve, reject) => {
  1323. const audio = uni.createInnerAudioContext();
  1324. audio.src = audioUrl;
  1325. let resolved = false;
  1326. // 监听音频加载完成事件
  1327. audio.onCanplay(() => {
  1328. if (!resolved && audio.duration && audio.duration > 0) {
  1329. resolved = true;
  1330. resolve(audio.duration);
  1331. audio.destroy();
  1332. }
  1333. });
  1334. // 监听音频元数据加载完成事件
  1335. audio.onLoadedmetadata = () => {
  1336. if (!resolved && audio.duration && audio.duration > 0) {
  1337. resolved = true;
  1338. resolve(audio.duration);
  1339. audio.destroy();
  1340. }
  1341. };
  1342. // 监听音频时长更新事件
  1343. audio.onDurationChange = () => {
  1344. if (!resolved && audio.duration && audio.duration > 0) {
  1345. resolved = true;
  1346. resolve(audio.duration);
  1347. audio.destroy();
  1348. }
  1349. };
  1350. // 如果以上方法都無法獲取時長,嘗試播放一小段來獲取時長
  1351. audio.onPlay(() => {
  1352. if (!resolved) {
  1353. setTimeout(() => {
  1354. if (!resolved && audio.duration && audio.duration > 0) {
  1355. resolved = true;
  1356. resolve(audio.duration);
  1357. audio.destroy();
  1358. }
  1359. }, 100); // 播放100ms後檢查時長
  1360. }
  1361. });
  1362. audio.onError((error) => {
  1363. console.error('音频加载失败:', error);
  1364. if (!resolved) {
  1365. resolved = true;
  1366. reject(error);
  1367. audio.destroy();
  1368. }
  1369. });
  1370. // 設置較長的超時時間,並在超時前嘗試播放
  1371. setTimeout(() => {
  1372. if (!resolved) {
  1373. audio.play();
  1374. }
  1375. }, 1000);
  1376. // 最終超時處理
  1377. setTimeout(() => {
  1378. if (!resolved) {
  1379. console.warn('獲取音頻時長超時,使用默認值');
  1380. resolved = true;
  1381. reject(new Error('获取音频时长超时'));
  1382. audio.destroy();
  1383. }
  1384. }, 5000);
  1385. });
  1386. },
  1387. // 音频控制方法 - 这些方法现在由AudioControls组件处理
  1388. // 保留一些简单的接口方法用于与AudioControls组件通信
  1389. // 判断当前文本是否应该高亮 - 这个方法需要保留,因为它用于模板渲染
  1390. isTextHighlighted(page, index) {
  1391. // 只有当前页面且是文本类型才可能高亮
  1392. if (page !== this.bookPages[this.currentPage - 1]) return false;
  1393. // 计算当前页面中text类型元素的索引
  1394. let textIndex = 0;
  1395. for (let i = 0; i <= index; i++) {
  1396. if (page[i].type === 'text') {
  1397. if (i === index) {
  1398. const shouldHighlight = textIndex === this.currentHighlightIndex;
  1399. if (shouldHighlight) {
  1400. }
  1401. return shouldHighlight;
  1402. }
  1403. textIndex++;
  1404. }
  1405. }
  1406. return false;
  1407. },
  1408. // 判断划线重点卡片中的文本是否应该高亮
  1409. isCardTextHighlighted(page, index) {
  1410. // 只有当前页面且是文本类型才可能高亮
  1411. if (page !== this.bookPages[this.currentPage - 1]) return false;
  1412. // 计算当前页面中text类型元素的索引
  1413. let textIndex = 0;
  1414. for (let i = 0; i <= index; i++) {
  1415. if (page[i].type === 'text') {
  1416. if (i === index) {
  1417. return textIndex === this.currentHighlightIndex;
  1418. }
  1419. textIndex++;
  1420. }
  1421. }
  1422. return false;
  1423. },
  1424. async previousPage() {
  1425. if (this.currentPage > 1) {
  1426. this.currentPage--;
  1427. // 获取对应页面的数据(如果还没有获取过)
  1428. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1429. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1430. }
  1431. }
  1432. },
  1433. async nextPage() {
  1434. if (this.currentPage < this.bookPages.length) {
  1435. this.currentPage++;
  1436. // 获取对应页面的数据(如果还没有获取过)
  1437. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1438. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1439. }
  1440. }
  1441. },
  1442. toggleSound() {
  1443. // 检查是否正在加载音频,如果是则阻止音色切换
  1444. if (this.isAudioLoading) {
  1445. uni.showToast({
  1446. title: '音频加载中,请稍后再试',
  1447. icon: 'none',
  1448. duration: 2000
  1449. });
  1450. return;
  1451. }
  1452. // 检查AudioControls组件是否正在加载音频
  1453. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls && this.$refs.customTabbar.$refs.audioControls.isAudioLoading) {
  1454. uni.showToast({
  1455. title: '音频加载中,请稍后再试',
  1456. icon: 'none',
  1457. duration: 2000
  1458. });
  1459. return;
  1460. }
  1461. console.log('音色切换')
  1462. uni.navigateTo({
  1463. url: '/subPages/home/music?voiceId=' + this.voiceId
  1464. })
  1465. },
  1466. unlockBook() {
  1467. console.log('解锁全书')
  1468. // 这里可以跳转到会员页面或者调用解锁接口
  1469. uni.navigateTo({
  1470. url: '/subPages/member/recharge'
  1471. })
  1472. },
  1473. // 跳转到下一课
  1474. async goToNextCourse() {
  1475. if (!this.hasNextCourse) {
  1476. uni.showToast({
  1477. title: '已经是最后一课了',
  1478. icon: 'none',
  1479. duration: 2000
  1480. });
  1481. return;
  1482. }
  1483. try {
  1484. // 找到当前课程在课程列表中的索引
  1485. const currentCourseIndex = this.courseList.findIndex(course => course.id == this.courseId);
  1486. if (currentCourseIndex >= 0 && currentCourseIndex < this.courseList.length - 1) {
  1487. // 获取下一课的ID
  1488. const nextCourse = this.courseList[currentCourseIndex + 1];
  1489. console.log('跳转到下一课:', nextCourse);
  1490. // 切换到下一课
  1491. await this.selectCourse(nextCourse.id);
  1492. uni.showToast({
  1493. title: `已切换到第${currentCourseIndex + 2}`,
  1494. icon: 'success',
  1495. duration: 2000
  1496. });
  1497. }
  1498. } catch (error) {
  1499. console.error('跳转下一课失败:', error);
  1500. uni.showToast({
  1501. title: '跳转失败,请重试',
  1502. icon: 'none',
  1503. duration: 2000
  1504. });
  1505. }
  1506. },
  1507. // 回到开始(当前课程的第一页)
  1508. async backToStart() {
  1509. try {
  1510. // 回到当前课程的第一页
  1511. this.currentPage = 1;
  1512. console.log('回到开始,跳转到第一页');
  1513. // 获取第一页的数据(如果还没有获取过)
  1514. if (this.courseIdList[0] && this.bookPages[0].length === 0) {
  1515. await this.getBookPages(this.courseIdList[0]);
  1516. }
  1517. uni.showToast({
  1518. title: '已回到第一页',
  1519. icon: 'success',
  1520. duration: 2000
  1521. });
  1522. } catch (error) {
  1523. console.error('回到开始失败:', error);
  1524. uni.showToast({
  1525. title: '操作失败,请重试',
  1526. icon: 'none',
  1527. duration: 2000
  1528. });
  1529. }
  1530. },
  1531. async goToPage(page) {
  1532. this.currentPage = page
  1533. console.log('跳转到页面:', page)
  1534. // 获取对应页面的数据(如果还没有获取过)
  1535. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1536. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1537. }
  1538. },
  1539. async onSwiperChange(e) {
  1540. this.currentPage = e.detail.current + 1
  1541. // 获取对应页面的数据(如果还没有获取过)
  1542. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1543. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1544. }
  1545. },
  1546. async getCourseList(id) {
  1547. const res = await this.$api.book.coursePage({
  1548. id: id
  1549. })
  1550. if (res.code === 200) {
  1551. // 课程切换时,先清理音频控制组件的所有数据
  1552. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1553. this.$refs.customTabbar.$refs.audioControls.resetForCourseChange();
  1554. }
  1555. // 清空当前页面相关数据
  1556. this.currentPage = 1; // 重置到第一页
  1557. this.currentCourse = 1; // 重置当前课程索引
  1558. this.currentWordMeaning = null; // 清空单词释义
  1559. this.currentWordAudio = null; // 清空单词音频
  1560. this.currentHighlightIndex = -1; // 清空高亮索引
  1561. // 清理单词音频缓存
  1562. this.clearWordAudioCache();
  1563. // 重新初始化课程数据
  1564. this.courseIdList = res.result.map(item => item.id)
  1565. // 初始化二维数组 换一种方式
  1566. this.bookPages = this.courseIdList.map(() => [])
  1567. // 初始化标题数组
  1568. this.pageTitles = this.courseIdList.map(() => '')
  1569. // 初始化页面类型数组
  1570. this.pageTypes = this.courseIdList.map(() => '')
  1571. // 初始化页面单词数组
  1572. this.pageWords = this.courseIdList.map(() => [])
  1573. // 初始化滚动位置数组
  1574. this.scrollTops = this.courseIdList.map(() => 0)
  1575. // 初始化第一页
  1576. if (this.courseIdList.length > 0) {
  1577. await this.getBookPages(this.courseIdList[0])
  1578. // 课程切换后,确保音频控件能正确加载新课程的音频
  1579. // 使用$nextTick确保DOM和数据都已更新
  1580. this.$nextTick(async () => {
  1581. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1582. try {
  1583. // 直接调用getCurrentPageAudio方法,更可靠
  1584. await this.$refs.customTabbar.$refs.audioControls.getCurrentPageAudio();
  1585. } catch (error) {
  1586. console.error('课程切换后音频加载失败:', error);
  1587. }
  1588. }
  1589. });
  1590. // 预加载后续几页的内容(异步执行,不阻塞当前页面显示)
  1591. this.preloadNextPages()
  1592. }
  1593. }
  1594. },
  1595. async getBookPages(id) {
  1596. const res = await this.$api.book.coursesPageDetail({
  1597. id: id
  1598. })
  1599. if (res.code === 200) {
  1600. // 使用$set确保响应式更新
  1601. const rawPageData = JSON.parse(res.result.content)
  1602. console.log('获取到的原始页面数据:', rawPageData)
  1603. // 过滤掉无效的数据项
  1604. const filteredPageData = rawPageData.filter(item => {
  1605. return item && typeof item === 'object' && (item.type || item.content)
  1606. })
  1607. console.log('过滤后的页面数据:', filteredPageData)
  1608. // 确保当前页面存在
  1609. if (this.currentPage - 1 < this.bookPages.length) {
  1610. this.$set(this.bookPages, this.currentPage - 1, filteredPageData)
  1611. // 保存页面标题
  1612. this.$set(this.pageTitles, this.currentPage - 1, res.result.title || '')
  1613. // 保存页面类型
  1614. this.$set(this.pageTypes, this.currentPage - 1, res.result.type || '')
  1615. // 保存页面单词释义数据
  1616. this.$set(this.pageWords, this.currentPage - 1, res.result.words || [])
  1617. // 保存页面付费状态
  1618. this.$set(this.pagePay, this.currentPage - 1, res.result.pay || 'N')
  1619. }
  1620. }
  1621. },
  1622. // 获取课程列表
  1623. async getCoursePageList(bookId) {
  1624. const res = await this.$api.book.course({
  1625. id: bookId
  1626. })
  1627. if (res.code === 200) {
  1628. this.courseList = res.result.records
  1629. // 打上序列号
  1630. this.courseList = this.courseList.map((item, index) => ({
  1631. ...item,
  1632. index,
  1633. }))
  1634. }
  1635. },
  1636. // 清理音频缓存
  1637. clearAudioCache() {
  1638. this.audioCache = {};
  1639. },
  1640. // 清理單詞語音緩存
  1641. clearWordAudioCache() {
  1642. this.wordAudioCache = {};
  1643. },
  1644. // 限制缓存大小,保留最近访问的页面
  1645. limitCacheSize(maxSize = 10) {
  1646. const cacheKeys = Object.keys(this.audioCache);
  1647. if (cacheKeys.length > maxSize) {
  1648. // 删除最旧的缓存项
  1649. const keysToDelete = cacheKeys.slice(0, cacheKeys.length - maxSize);
  1650. keysToDelete.forEach(key => {
  1651. delete this.audioCache[key];
  1652. });
  1653. }
  1654. },
  1655. // 预加载后续页面内容
  1656. async preloadNextPages() {
  1657. try {
  1658. // 优化策略:只预加载接下来的2-3页内容,避免过多请求
  1659. const preloadCount = Math.min(3, this.courseIdList.length - 1); // 预加载3页或剩余页数
  1660. // 串行预加载,避免并发请求过多
  1661. for (let i = 1; i <= preloadCount; i++) {
  1662. if (i < this.courseIdList.length && this.bookPages[i].length === 0) {
  1663. try {
  1664. await this.preloadSinglePage(this.courseIdList[i], i);
  1665. // 每页之间间隔400ms,提高预加载效率
  1666. if (i < preloadCount) {
  1667. await new Promise(resolve => setTimeout(resolve, 0));
  1668. }
  1669. } catch (error) {
  1670. console.error(`预加载第${i + 1}页失败:`, error);
  1671. // 继续预加载下一页
  1672. }
  1673. }
  1674. }
  1675. // 延迟800ms后再通知AudioControls组件开始预加载音频,提高响应速度
  1676. setTimeout(() => {
  1677. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1678. this.$refs.customTabbar.$refs.audioControls.startPreloadAudio();
  1679. }
  1680. }, 800);
  1681. } catch (error) {
  1682. console.error('预加载页面内容失败:', error);
  1683. }
  1684. },
  1685. // 预加载单个页面
  1686. async preloadSinglePage(courseId, pageIndex) {
  1687. try {
  1688. const res = await this.$api.book.coursesPageDetail({
  1689. id: courseId
  1690. });
  1691. if (res.code === 200) {
  1692. const rawPageData = JSON.parse(res.result.content);
  1693. const filteredPageData = rawPageData.filter(item => {
  1694. return item && typeof item === 'object' && (item.type || item.content);
  1695. });
  1696. // 使用$set确保响应式更新
  1697. this.$set(this.bookPages, pageIndex, filteredPageData);
  1698. this.$set(this.pageTitles, pageIndex, res.result.title || '');
  1699. this.$set(this.pageTypes, pageIndex, res.result.type || '');
  1700. this.$set(this.pageWords, pageIndex, res.result.words || []);
  1701. this.$set(this.pagePay, pageIndex, res.result.pay || 'N');
  1702. }
  1703. } catch (error) {
  1704. console.error(`预加载第${pageIndex + 1}页失败:`, error);
  1705. throw error;
  1706. }
  1707. },
  1708. // 自動加載第一頁音頻並播放
  1709. async autoLoadAndPlayFirstPage() {
  1710. try {
  1711. // 確保當前是第一頁且需要加載音頻
  1712. if (this.currentPage === 1 && this.shouldLoadAudio) {
  1713. // 加載音頻
  1714. await this.getCurrentPageAudio();
  1715. // 檢查是否成功加載音頻
  1716. if (this.currentPageAudios && this.currentPageAudios.length > 0) {
  1717. // getCurrentPageAudio方法已經處理了第一個音頻的播放,這裡不需要再次調用playAudio
  1718. } else {
  1719. }
  1720. } else {
  1721. }
  1722. } catch (error) {
  1723. console.error('自動加載和播放音頻失敗:', error);
  1724. }
  1725. },
  1726. },
  1727. async onLoad(args) {
  1728. this.$scrollTo('imageRef')
  1729. // 初始化audioManager事件监听
  1730. this.initAudioManagerListeners();
  1731. // 监听音色切换事件,传递给AudioControls组件处理
  1732. uni.$on('selectVoice', async (voiceId) => {
  1733. if (this.voiceId === voiceId) {
  1734. return;
  1735. }
  1736. // 检查是否正在加载音频,如果是则阻止音色切换
  1737. if (this.isAudioLoading || (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls && this.$refs.customTabbar.$refs.audioControls.isAudioLoading)) {
  1738. uni.showToast({
  1739. title: '音频加载中,请稍后再试',
  1740. icon: 'none',
  1741. duration: 2000
  1742. });
  1743. return;
  1744. }
  1745. // 更新本地音色ID
  1746. this.voiceId = voiceId;
  1747. // 同步音色设置到audioManager
  1748. audioManager.setGlobalVoiceId(voiceId);
  1749. // 清理單詞語音資源
  1750. this.clearWordAudioCache();
  1751. // 停止当前播放的音频(现在由audioManager统一管理)
  1752. audioManager.stopCurrentAudio();
  1753. // 通知AudioControls组件处理音色切换
  1754. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1755. try {
  1756. // 传入选项:preloadAllPages: true 表示要预加载所有页面的音频
  1757. await this.$refs.customTabbar.$refs.audioControls.handleVoiceChange(voiceId, {
  1758. preloadAllPages: true
  1759. });
  1760. } catch (error) {
  1761. console.error('音色切换处理失败:', error);
  1762. }
  1763. }
  1764. })
  1765. this.courseId = args.courseId
  1766. this.currentCourse = args.courseId // 同时设置 currentCourse
  1767. this.memberId = args.memberId
  1768. // 先获取点进来的课程的页面列表
  1769. await Promise.all([this.getVoiceList(), this.getMemberInfo(), this.getCourseList(this.courseId), this.getCoursePageList(args.bookId)])
  1770. // 页面加载完成后,通知AudioControls组件自动加载第一页音频
  1771. this.$nextTick(() => {
  1772. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1773. this.$refs.customTabbar.$refs.audioControls.autoLoadAndPlayFirstPage();
  1774. }
  1775. });
  1776. },
  1777. // 页面卸载时清理资源
  1778. onUnload() {
  1779. uni.$off('selectVoice')
  1780. // 0. 清理滚动防抖定时器
  1781. if (this.scrollDebounceTimer) {
  1782. clearTimeout(this.scrollDebounceTimer);
  1783. this.scrollDebounceTimer = null;
  1784. }
  1785. // 1. 清理单词语音资源
  1786. if (this.currentWordAudio) {
  1787. try {
  1788. this.currentWordAudio.destroy();
  1789. } catch (error) {
  1790. console.error('销毁单词音频实例失败:', error);
  1791. }
  1792. this.currentWordAudio = null;
  1793. }
  1794. // 2. 清理单词语音缓存
  1795. this.clearWordAudioCache();
  1796. // 3. 停止单词音频播放状态
  1797. this.isWordAudioPlaying = false;
  1798. // 4. 通知AudioControls组件清理资源
  1799. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1800. this.$refs.customTabbar.$refs.audioControls.destroyAudio();
  1801. }
  1802. // 5. 清理全局音频实例(防止遗漏)
  1803. try {
  1804. // 获取所有可能的音频上下文并销毁
  1805. if (typeof wx !== 'undefined' && wx.getBackgroundAudioManager) {
  1806. const bgAudio = wx.getBackgroundAudioManager();
  1807. if (bgAudio) {
  1808. bgAudio.stop();
  1809. }
  1810. }
  1811. } catch (error) {
  1812. console.error('清理背景音频失败:', error);
  1813. }
  1814. },
  1815. // 页面隐藏时暂停音频
  1816. onHide() {
  1817. // 1. 暂停单词音频
  1818. if (this.currentWordAudio && this.isWordAudioPlaying) {
  1819. try {
  1820. this.currentWordAudio.pause();
  1821. this.isWordAudioPlaying = false;
  1822. } catch (error) {
  1823. console.error('暂停单词音频失败:', error);
  1824. }
  1825. }
  1826. // 2. 通知AudioControls组件暂停音频
  1827. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1828. this.$refs.customTabbar.$refs.audioControls.pauseOnHide();
  1829. }
  1830. }
  1831. }
  1832. </script>
  1833. <style lang="scss" scoped>
  1834. .book-container {
  1835. width: 100%;
  1836. min-height: 100vh;
  1837. background-color: #F8F8F8;
  1838. position: relative;
  1839. overflow: hidden;
  1840. }
  1841. .custom-navbar {
  1842. position: fixed;
  1843. top: 0;
  1844. left: 0;
  1845. right: 0;
  1846. background-color: #F8F8F8;
  1847. z-index: 1000;
  1848. transition: transform 0.3s ease;
  1849. &.navbar-hidden {
  1850. transform: translateY(-100%);
  1851. }
  1852. }
  1853. .navbar-content {
  1854. display: flex;
  1855. align-items: center;
  1856. justify-content: space-between;
  1857. padding: 20rpx 32rpx;
  1858. // padding-top: calc(20rpx + var(--status-bar-height, 0));
  1859. height: 60rpx;
  1860. }
  1861. .navbar-left,
  1862. .navbar-right {
  1863. width: 80rpx;
  1864. display: flex;
  1865. align-items: center;
  1866. }
  1867. .navbar-right {
  1868. justify-content: flex-end;
  1869. flex: 1;
  1870. }
  1871. .navbar-title {
  1872. transform: translateX(-50rpx);
  1873. flex: 1;
  1874. text-align: center;
  1875. font-family: PingFang SC;
  1876. font-weight: 500;
  1877. font-size: 32rpx;
  1878. color: #262626;
  1879. line-height: 48rpx;
  1880. }
  1881. .content-swiper {
  1882. flex: 1;
  1883. // min-height: calc(100vh - 100rpx);
  1884. // margin-top: 100rpx;
  1885. height: 100vh;
  1886. }
  1887. .swiper-item {
  1888. min-height: 100vh;
  1889. // background-color: red;
  1890. }
  1891. .content-area {
  1892. flex: 1;
  1893. padding: 30rpx 40rpx 100rpx;
  1894. /* #ifndef H5 */
  1895. padding: 100rpx 40rpx;
  1896. /* #endif */
  1897. // padding-top: ;
  1898. // background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);
  1899. min-height: 100%;
  1900. box-sizing: border-box;
  1901. overflow-y: auto;
  1902. .title {
  1903. font-family: PingFang SC;
  1904. font-weight: 500;
  1905. font-size: 34rpx;
  1906. text-align: center;
  1907. color: #181818;
  1908. line-height: 48rpx;
  1909. margin-bottom: 32rpx;
  1910. }
  1911. .image-container {
  1912. width: 100%;
  1913. display: flex;
  1914. justify-content: center;
  1915. align-items: center;
  1916. margin: 30rpx 0;
  1917. /* 平板设备适配 */
  1918. @media screen and (min-width: 768px) {
  1919. margin: 40rpx 0;
  1920. }
  1921. }
  1922. .content-image {
  1923. width: 100%;
  1924. height: auto;
  1925. //max-width: 600rpx;
  1926. /* 限制最大宽度,避免在大屏设备上过大 */
  1927. display: block;
  1928. border-radius: 12rpx;
  1929. /* 添加圆角,提升视觉效果 */
  1930. box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  1931. /* 添加阴影,增强层次感 */
  1932. /* 平板设备适配 */
  1933. // @media screen and (min-width: 768px) {
  1934. // max-width: 500rpx;
  1935. // }
  1936. }
  1937. .video-content {
  1938. width: 100%;
  1939. height: auto;
  1940. margin: 30rpx auto;
  1941. position: relative;
  1942. .video-player {
  1943. // height: 100%;
  1944. width: 100%;
  1945. height: 60vw;
  1946. // margin: 0 auto;
  1947. // height: auto;
  1948. }
  1949. .video-loading {
  1950. position: absolute;
  1951. top: 50%;
  1952. left: 50%;
  1953. transform: translate(-50%, -50%);
  1954. color: #666;
  1955. font-size: 28rpx;
  1956. }
  1957. }
  1958. }
  1959. .card-content {
  1960. background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);
  1961. display: flex;
  1962. flex-direction: column;
  1963. gap: 32rpx;
  1964. min-height: 1172rpx;
  1965. margin-top: 20rpx;
  1966. border-radius: 32rpx;
  1967. // height: 100%;
  1968. padding: 20rpx;
  1969. padding-bottom: 100rpx;
  1970. // margin: 0
  1971. border: 1px solid #FFFFFF;
  1972. box-sizing: border-box;
  1973. .card-line {
  1974. display: flex;
  1975. align-items: center;
  1976. // margin-bottom: 20rpx;
  1977. padding: 20rpx;
  1978. padding-bottom: 0;
  1979. }
  1980. .card-line-image {
  1981. width: 48rpx;
  1982. height: 48rpx;
  1983. margin-right: 16rpx;
  1984. }
  1985. .card-line-text {
  1986. font-family: PingFang SC;
  1987. font-weight: 600;
  1988. font-size: 30rpx;
  1989. line-height: 48rpx;
  1990. color: #3B3D3D;
  1991. }
  1992. .card-image {
  1993. // width: 590rpx;
  1994. width: 100%;
  1995. height: 268rpx;
  1996. border-radius: 24rpx;
  1997. margin: 30rpx auto;
  1998. // margin-bottom: 20rpx;
  1999. }
  2000. // .english-text {
  2001. // display: block;
  2002. // font-family: PingFang SC;
  2003. // font-weight: 600;
  2004. // font-size: 32rpx;
  2005. // line-height: 48rpx;
  2006. // color: #3B3D3D;
  2007. // // margin-bottom: 16rpx;
  2008. // }
  2009. // .english-text-container {
  2010. // display: flex;
  2011. // flex-wrap: wrap;
  2012. // align-items: baseline;
  2013. // }
  2014. // .english-token {
  2015. // font-family: PingFang SC;
  2016. // font-weight: 600;
  2017. // font-size: 32rpx;
  2018. // line-height: 48rpx;
  2019. // color: #3B3D3D;
  2020. // margin-right: 10rpx;
  2021. // }
  2022. .clickable-word {
  2023. background: $primary-color;
  2024. text-decoration: underline;
  2025. cursor: pointer;
  2026. transition: all 0.2s ease;
  2027. padding: 0 20rpx;
  2028. }
  2029. .clickable-word:hover {
  2030. background-color: rgba(0, 122, 255, 0.1);
  2031. border-radius: 4rpx;
  2032. }
  2033. .chinese-segment {
  2034. font-family: PingFang SC;
  2035. font-weight: 400;
  2036. font-size: 28rpx;
  2037. line-height: 48rpx;
  2038. color: #3B3D3D;
  2039. }
  2040. .clickable-keyword {
  2041. background: $primary-color;
  2042. text-decoration: underline;
  2043. cursor: pointer;
  2044. color: #fff !important;
  2045. transition: all 0.2s ease;
  2046. border-radius: 4rpx;
  2047. padding: 4rpx;
  2048. }
  2049. .clickable-keyword:hover {
  2050. background-color: rgba(0, 122, 255, 0.1);
  2051. }
  2052. .chinese-text {
  2053. display: block;
  2054. font-family: PingFang SC;
  2055. font-weight: 400;
  2056. font-size: 28rpx;
  2057. line-height: 48rpx;
  2058. color: #4F4F4F;
  2059. }
  2060. }
  2061. /* 会员限制页面样式 */
  2062. .member-content {
  2063. display: flex;
  2064. flex-direction: column;
  2065. align-items: center;
  2066. justify-content: center;
  2067. height: 90%;
  2068. background-color: #F8F8F8;
  2069. padding: 40rpx;
  2070. margin: -40rpx;
  2071. box-sizing: border-box;
  2072. }
  2073. .member-title {
  2074. font-family: PingFang SC;
  2075. font-weight: 500;
  2076. font-size: 40rpx;
  2077. line-height: 1;
  2078. color: #6f6f6f;
  2079. text-align: center;
  2080. margin-bottom: 48rpx;
  2081. }
  2082. .member-button {
  2083. width: 670rpx;
  2084. height: 72rpx;
  2085. background: #06DADC;
  2086. border-radius: 200rpx;
  2087. display: flex;
  2088. align-items: center;
  2089. justify-content: center;
  2090. }
  2091. .member-button-text {
  2092. font-family: PingFang SC;
  2093. font-weight: 400;
  2094. font-size: 30rpx;
  2095. color: #FFFFFF;
  2096. }
  2097. // .video-content {
  2098. // width: 100%;
  2099. // height: auto;
  2100. // // margin: 200rpx -40rpx 0;
  2101. // // height: 500rpx;
  2102. // background-color: #FFFFFF;
  2103. // // padding: 40rpx;
  2104. // border-radius: 24rpx;
  2105. // display: flex;
  2106. // align-items: center;
  2107. // justify-content: center;
  2108. // .video-player{
  2109. // width: 100%;
  2110. // margin: 0 auto;
  2111. // height: auto;
  2112. // }
  2113. // }
  2114. .text-content {
  2115. // background-color: #F6F6F6;
  2116. box-sizing: border-box;
  2117. &>view {
  2118. padding: 20rpx;
  2119. }
  2120. }
  2121. .content-text {
  2122. font-family: PingFang SC;
  2123. // font-weight: 400;
  2124. font-size: 28rpx;
  2125. color: #3B3D3D;
  2126. line-height: 48rpx;
  2127. letter-spacing: 0;
  2128. text-align: justify;
  2129. word-break: break-all;
  2130. transition: all 0.3s ease;
  2131. }
  2132. .clickable-text {
  2133. cursor: pointer;
  2134. &:active {
  2135. background-color: rgba(6, 218, 220, 0.1);
  2136. border-radius: 4rpx;
  2137. }
  2138. }
  2139. .lead-text {
  2140. background: #06dadc12;
  2141. // background: #fffbe6;#06dadc
  2142. /* 柔和的提示背景 */
  2143. // border: 1px solid #ffe58f;
  2144. border-radius: 8px;
  2145. // padding: 10rpx 20rpx;
  2146. /* 添加平滑过渡动画 */
  2147. transition: all 0.3s ease;
  2148. }
  2149. .introduction-text {
  2150. background: #fffbe6;
  2151. border: 1px solid #ffe58f;
  2152. border-radius: 8px;
  2153. padding: 10rpx 20rpx;
  2154. }
  2155. .text-highlight {
  2156. background-color: rgba(255, 248, 220, 0.8);
  2157. /* 温暖的米黄色,对眼睛友好 */
  2158. border-left: 4rpx solid #ffd700;
  2159. /* 左侧金色边框作为朗读指示 */
  2160. padding: 4rpx 8rpx;
  2161. border-radius: 6rpx;
  2162. box-shadow: 0 2rpx 6rpx rgba(255, 215, 0, 0.15);
  2163. /* 柔和的阴影 */
  2164. /* 添加平滑过渡动画 */
  2165. transition: all 0.3s ease;
  2166. }
  2167. </style>