四零语境前端代码仓库
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.

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