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

2030 lines
59 KiB

1 month ago
1 month ago
2 weeks ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
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
  19. class="content-swiper"
  20. :current="currentPage - 1"
  21. @change="onSwiperChange"
  22. >
  23. <swiper-item
  24. v-for="(page, index) in bookPages"
  25. :key="index"
  26. class="swiper-item"
  27. >
  28. <scroll-view
  29. scroll-y
  30. :scroll-top="scrollTops[index] || 0"
  31. :scroll-with-animation="true"
  32. style="height: 100vh;"
  33. class="scroll-container"
  34. @scroll="onScroll"
  35. >
  36. <view class="content-area" @click="toggleNavbar">
  37. <view class="title">{{ currentPageTitle }}</view>
  38. <!-- 会员限制页面 -->
  39. <view v-if="!isMember && pagePay[index] === 'Y'" class="member-content" >
  40. <text class="member-title">{{ pageTitles[index] }}</text>
  41. <view class="member-button" @click.stop="unlockBook">
  42. <text class="member-button-text">升级会员解锁</text>
  43. </view>
  44. </view>
  45. <!-- 图片卡片页面 -->
  46. <view class="card-content" v-else-if="pageTypes[index] === '1'">
  47. <view class="card-line">
  48. <image :src="configParamContent('highlight_icon')" class="card-line-image" mode="aspectFill" />
  49. <text class="card-line-text">划线重点</text>
  50. </view>
  51. <view v-for="(item, itemIndex) in page" :key="itemIndex">
  52. <image class="card-image" v-if="item && item.type === 'image'" :src="item.imageUrl" mode="aspectFill" ></image>
  53. <view class="english-text-container clickable-text" v-else-if="item && item.type === 'text' && item.language === 'en' && item.content" @click.stop="handleTextClick(item.content, item, index)" >
  54. <text
  55. v-for="(token, tokenIndex) in splitEnglishSentence(item.content)"
  56. :key="tokenIndex"
  57. :class="['english-token', { 'clickable-word': token.isWord && findWordDefinition(token.text) }]"
  58. @click.stop="token.isWord && findWordDefinition(token.text) ? handleWordClick(token.text) : null"
  59. user-select
  60. :style="item.style"
  61. >{{ token.text }}</text>
  62. </view>
  63. <view v-else-if="item && item.type === 'text' && item.language === 'zh' && item.content" @click.stop="handleTextClick(item.content, item, index)">
  64. <text
  65. v-for="(segment, segmentIndex) in processChineseText(item.content)"
  66. :key="segmentIndex"
  67. :class="['chinese-segment', { 'clickable-keyword': segment.isKeyword }]"
  68. @click.stop="segment.isKeyword ? handleChineseKeywordClick(segment.keywordData) : null"
  69. user-select
  70. :style="item.style"
  71. >{{ segment.text }}</text>
  72. </view>
  73. </view>
  74. </view>
  75. <view v-else>
  76. <view v-for="(item, itemIndex) in page" :key="itemIndex">
  77. <!-- 文本页面 -->
  78. <view v-if="item && item.type === 'text' && item.content" class="text-content" >
  79. <view :class="{ 'lead-text': isTextHighlighted(page, itemIndex) }" @click.stop="handleTextClick(item.content, item, index)" :ref="`textRef_${index}_${itemIndex}`">
  80. <text
  81. v-if="!item.isLead"
  82. class="content-text clickable-text"
  83. :style="item.style"
  84. user-select
  85. >
  86. {{ item.content }}
  87. </text>
  88. <view v-else-if="item.isLead" class="content-text clickable-text lead-text" :style="item.style" user-select>{{ item.content }}</view>
  89. </view>
  90. </view>
  91. <!-- 图片页面 -->
  92. <view v-else-if="item.type === 'image'" class="image-container" :ref="`imageRef_${index}_${itemIndex}`">
  93. <image class="content-image" :src="item.imageUrl" mode="widthFix"></image>
  94. </view>
  95. <!-- 视频页面 -->
  96. <view v-else-if="item.type === 'video'" class="video-content" @click.stop>
  97. <!-- 视频加载状态 -->
  98. <view v-if="videoLoading" class="video-loading">
  99. <text class="loading-text">视频加载中...</text>
  100. </view>
  101. <!-- 视频播放器 -->
  102. <video
  103. v-else
  104. :src="item.url"
  105. class="video-player"
  106. controls
  107. :poster="item.coverUrl"
  108. @loadstart="onVideoLoadStart"
  109. @loadeddata="onVideoLoadStart"
  110. @error="onVideoError"
  111. ></video>
  112. </view>
  113. </view>
  114. </view>
  115. </view>
  116. </scroll-view>
  117. </swiper-item>
  118. </swiper>
  119. <!-- 自定义底部控制栏 -->
  120. <CustomTabbar
  121. :show-navbar="showNavbar"
  122. :current-page="currentPage"
  123. :course-id="courseId"
  124. :voice-id="voiceId"
  125. :book-pages="bookPages"
  126. :is-text-page="isTextPage"
  127. :should-load-audio="shouldLoadAudio"
  128. :is-member="isMember"
  129. :current-page-requires-member="currentPageRequiresMember"
  130. :page-pay="pagePay"
  131. :is-word-audio-playing="isWordAudioPlaying"
  132. @toggle-course-popup="toggleCoursePopup"
  133. @toggle-sound="toggleSound"
  134. @go-to-page="goToPage"
  135. @previous-page="previousPage"
  136. @next-page="nextPage"
  137. @audio-state-change="onAudioStateChange"
  138. @highlight-change="onHighlightChange"
  139. @voice-change-complete="onVoiceChangeComplete"
  140. @voice-change-error="onVoiceChangeError"
  141. @page-data-needed="onPageDataNeeded"
  142. ref="customTabbar"
  143. />
  144. <!-- 课程选择弹出窗 -->
  145. <CoursePopup
  146. :style="{zIndex: 10000}"
  147. :course-list="courseList"
  148. :current-course="currentCourse"
  149. :is-reversed="isReversed"
  150. @toggle-sort="toggleSort"
  151. @select-course="selectCourse"
  152. ref="coursePopup"
  153. />
  154. <!-- 释义弹出窗 -->
  155. <MeaningPopup
  156. :style="{zIndex: 10000}"
  157. :current-word-meaning="currentWordMeaning"
  158. @close-meaning-popup="closeMeaningPopup"
  159. @repeat-word-audio="repeatWordAudio"
  160. ref="meaningPopup"
  161. />
  162. </view>
  163. </template>
  164. <script>
  165. import AudioControls from './AudioControls.vue'
  166. import CustomTabbar from './components/CustomTabbar.vue'
  167. import CoursePopup from './components/CoursePopup.vue'
  168. import MeaningPopup from './components/MeaningPopup.vue'
  169. export default {
  170. components: {
  171. AudioControls,
  172. CustomTabbar,
  173. CoursePopup,
  174. MeaningPopup
  175. },
  176. data() {
  177. return {
  178. isMember: false,
  179. memberId: '',
  180. voiceId: null,
  181. courseId: '',
  182. showNavbar: true,
  183. currentPage: 1,
  184. currentCourse: 1, // 当前课程索引
  185. currentWordMeaning: null, // 当前显示的单词释义
  186. isReversed: false, // 是否倒序显示
  187. // 文本高亮相关 - 由AudioControls组件管理,这里只保留必要的接口
  188. currentHighlightIndex: -1, // 当前高亮的文本索引,用于模板渲染
  189. wordAudioCache: {}, // 單詞語音緩存
  190. currentWordAudio: null, // 當前播放的單詞音頻實例
  191. isWordAudioPlaying: false, // 是否有单词音频正在播放
  192. // 音频状态相关 - 这些状态现在由AudioControls组件管理
  193. // 保留这些属性用于与AudioControls组件的数据同步
  194. isAudioLoading: false, // 音频是否正在加载
  195. hasAudioData: false, // 是否有音频数据
  196. audioLoadFailed: false, // 音频加载是否失败
  197. // 视频状态相关
  198. videoLoading: false, // 视频是否正在加载
  199. // 滚动相关
  200. scrollTops: [], // 每个页面的scroll-view滚动位置数组
  201. courseIdList: [],
  202. bookTitle: '',
  203. courseList: [
  204. ],
  205. // 二维数组 代表每个页面
  206. bookPages: [
  207. ],
  208. // 存储每个页面的标题
  209. pageTitles: [],
  210. // 存储每个页面的type信息
  211. pageTypes: [],
  212. // 存储每个页面的单词释义数据
  213. pageWords: [],
  214. // 存储每个页面的付费状态
  215. pagePay: [],
  216. }
  217. },
  218. computed: {
  219. displayCourseList() {
  220. return this.isReversed ? [...this.courseList].reverse() : this.courseList;
  221. },
  222. // 判断当前页面是否为文字类型
  223. isTextPage() {
  224. // 如果是卡片页面(type为'1'),不显示音频控制栏
  225. if (this.currentPageType === '1') {
  226. return false;
  227. }
  228. const currentPageData = this.bookPages[this.currentPage - 1];
  229. // currentPageData是一个数组 其中的一个元素的type是text就会返回true
  230. return currentPageData && currentPageData.some(item => item.type === 'text');
  231. },
  232. // 判断当前页面是否需要加载音频(包括文本页面和卡片页面)
  233. shouldLoadAudio() {
  234. // 文本页面需要加载音频
  235. if (this.isTextPage) {
  236. return true;
  237. }
  238. // 卡片页面(type为'1')也需要加载音频以支持点击播放
  239. if (this.currentPageType === '1') {
  240. return true;
  241. }
  242. return false;
  243. },
  244. // 动态页面标题
  245. currentPageTitle() {
  246. return this.pageTitles[this.currentPage - 1] || this.bookTitle;
  247. },
  248. // 当前页面类型
  249. currentPageType() {
  250. return this.pageTypes[this.currentPage - 1] || '';
  251. },
  252. // 当前页面的单词释义数据
  253. currentPageWords() {
  254. return this.pageWords[this.currentPage - 1] || [];
  255. },
  256. // 当前页面是否需要会员
  257. currentPageRequiresMember() {
  258. return this.pagePay[this.currentPage - 1] === 'Y';
  259. }
  260. },
  261. // watch: {
  262. // scrollTops: {
  263. // handler(newVal, oldVal) {
  264. // console.log('📊 scrollTops变化:', {
  265. // currentPage: this.currentPage,
  266. // newScrollTops: newVal,
  267. // currentPageScrollTop: newVal[this.currentPage - 1]
  268. // });
  269. // },
  270. // deep: true
  271. // }
  272. // },
  273. methods: {
  274. // 处理scroll-view滚动事件
  275. onScroll(e) {
  276. // 更新当前页面的滚动位置
  277. const scrollTop = e.detail.scrollTop;
  278. const currentPageIndex = this.currentPage - 1;
  279. // 只有当滚动位置发生显著变化时才更新
  280. if (Math.abs((this.scrollTops[currentPageIndex] || 0) - scrollTop) > 5) {
  281. this.$set(this.scrollTops, currentPageIndex, scrollTop);
  282. }
  283. },
  284. // 视频事件处理方法
  285. onVideoLoadStart() {
  286. this.videoLoading = true;
  287. },
  288. onVideoCanPlay() {
  289. this.videoLoading = false;
  290. },
  291. onVideoError() {
  292. this.videoLoading = false;
  293. uni.showToast({
  294. title: '视频加载失败',
  295. icon: 'none',
  296. duration: 2000
  297. });
  298. },
  299. // 獲取用戶會員信息 判斷是否和傳參傳過來的會員id相同
  300. async getMemberInfo(){
  301. const memberRes = await this.$api.member.getUserMemberInfo()
  302. if (memberRes.code === 200) {
  303. this.isMember = memberRes.result.map(item => item.memberId).includes(this.memberId)
  304. }
  305. },
  306. // 处理AudioControls组件的事件
  307. onAudioStateChange(audioState) {
  308. // 更新高亮状态
  309. this.currentHighlightIndex = audioState.currentHighlightIndex;
  310. // 更新音频加载状态(用于控制UI显示)
  311. if (audioState.hasOwnProperty('isLoading')) {
  312. this.isAudioLoading = audioState.isLoading;
  313. }
  314. // 更新音频数据状态
  315. if (audioState.hasOwnProperty('hasAudioData')) {
  316. this.hasAudioData = audioState.hasAudioData;
  317. }
  318. // 更新音频加载失败状态
  319. if (audioState.hasOwnProperty('audioLoadFailed')) {
  320. this.audioLoadFailed = audioState.audioLoadFailed;
  321. }
  322. },
  323. // 处理页面数据需要重新加载的事件
  324. async onPageDataNeeded(pageNumber) {
  325. console.log('收到页面数据需要重新加载的请求,页面:', pageNumber);
  326. // 如果页面数据不存在或为空,重新获取
  327. if (!this.bookPages || this.bookPages.length === 0 || !this.bookPages[pageNumber - 1]) {
  328. console.log('页面数据不存在,重新获取页面数据');
  329. try {
  330. await this.getBookPages();
  331. console.log('页面数据重新获取完成');
  332. // 页面数据更新后,AudioControls组件的bookPages监听器会自动触发音频获取
  333. // 无需手动调用getCurrentPageAudio,避免重复调用
  334. } catch (error) {
  335. console.error('重新获取页面数据失败:', error);
  336. }
  337. } else {
  338. console.log('页面数据已存在,无需重新获取');
  339. }
  340. },
  341. // 处理音色切换完成事件
  342. onVoiceChangeComplete(data) {
  343. // 可以在这里添加一些UI反馈,比如显示切换成功的提示
  344. if (data.hasAudioData) {
  345. } else {
  346. }
  347. // 如果启用了预加载所有页面
  348. if (data.preloadAllPages) {
  349. // 可以显示一个提示,告诉用户正在后台加载
  350. uni.showToast({
  351. title: '正在加载新音色...',
  352. icon: 'loading',
  353. duration: 2000
  354. });
  355. }
  356. },
  357. // 处理音色切换错误事件
  358. onVoiceChangeError(error) {
  359. console.error('音色切换失败:', error);
  360. // 可以在这里显示错误提示给用户
  361. uni.showToast({
  362. title: '音色切换失败,请重试',
  363. icon: 'none',
  364. duration: 2000
  365. });
  366. },
  367. // 处理音频切换时的自动滚动
  368. // onScrollToText(refName) {
  369. // try {
  370. // console.log('🎯 onScrollToText 被调用:', refName);
  371. //
  372. // // 调用scrollTo插件
  373. // this.$scrollTo(refName);
  374. //
  375. // } catch (error) {
  376. // console.error('❌ onScrollToText 执行失败:', error);
  377. // }
  378. // },
  379. // 处理文本点击事件
  380. handleTextClick(textContent, item, pageIndex) {
  381. // console.log('🎯 ===== 文本点击事件开始 =====');
  382. // console.log('📝 点击文本:', textContent);
  383. // console.log('📄 textContent类型:', typeof textContent);
  384. // console.log('❓ textContent是否为undefined:', textContent === undefined);
  385. // console.log('📦 完整item对象:', item);
  386. // console.log('📝 item.content:', item ? item.content : 'item为空');
  387. // console.log('📖 当前页面索引:', this.currentPage);
  388. // console.log('👆 点击的页面索引:', pageIndex);
  389. // console.log('📊 当前页面类型:', this.currentPageType);
  390. // console.log('📄 是否为文本页面:', this.isTextPage);
  391. // console.log('📋 当前页面数据:', this.bookPages[this.currentPage - 1]);
  392. // console.log('📏 页面数据长度:', this.bookPages[this.currentPage - 1] ? this.bookPages[this.currentPage - 1].length : '页面不存在');
  393. // 检查音频播放状态
  394. // console.log('🎵 ===== 音频状态检查 =====');
  395. // console.log(' isWordAudioPlaying:', this.isWordAudioPlaying);
  396. // console.log(' currentWordAudio存在:', !!this.currentWordAudio);
  397. // console.log(' currentWordMeaning存在:', !!this.currentWordMeaning);
  398. if (this.isWordAudioPlaying) {
  399. // console.log('⚠️ 检测到单词音频正在播放状态,这可能会阻止句子音频播放');
  400. // console.log('🔄 尝试重置音频播放状态...');
  401. this.isWordAudioPlaying = false;
  402. // console.log('✅ 音频播放状态已重置');
  403. }
  404. // 检查是否点击的是当前页面
  405. if (pageIndex !== undefined && pageIndex !== this.currentPage - 1) {
  406. console.warn('⚠️ 点击的不是当前页面,忽略点击事件');
  407. // console.log(` 期望页面: ${this.currentPage - 1}, 点击页面: ${pageIndex}`);
  408. return;
  409. }
  410. // 验证参数有效性
  411. if (!item) {
  412. console.error('❌ handleTextClick: item参数为空');
  413. uni.showToast({
  414. title: '数据错误,请刷新页面',
  415. icon: 'none'
  416. });
  417. return;
  418. }
  419. // 如果textContent为undefined,尝试从item中获取
  420. if (!textContent && item && item.content) {
  421. textContent = item.content;
  422. // console.log('🔄 从item中获取到content:', textContent);
  423. }
  424. // 最终验证textContent
  425. if (!textContent || typeof textContent !== 'string' || textContent.trim() === '') {
  426. console.error('❌ handleTextClick: 无效的文本内容', textContent);
  427. // console.log(' textContent:', textContent);
  428. // console.log(' 类型:', typeof textContent);
  429. // console.log(' 是否为空字符串:', textContent === '');
  430. // console.log(' trim后是否为空:', textContent && textContent.trim() === '');
  431. uni.showToast({
  432. title: '文本内容无效',
  433. icon: 'none'
  434. });
  435. return;
  436. }
  437. // console.log('✅ 文本内容验证通过:', textContent);
  438. // console.log(' 文本长度:', textContent.length);
  439. // console.log(' 文本预览:', textContent.substring(0, 50) + (textContent.length > 50 ? '...' : ''));
  440. // 检查是否有音频控制组件的引用
  441. // console.log('🔍 检查音频控制组件引用...');
  442. // console.log(' customTabbar存在:', !!this.$refs.customTabbar);
  443. if (!this.$refs.customTabbar) {
  444. console.error('❌ customTabbar引用不存在');
  445. uni.showToast({
  446. title: '音频控制组件未准备好',
  447. icon: 'none'
  448. });
  449. return;
  450. }
  451. // console.log(' audioControls存在:', !!this.$refs.customTabbar.$refs.audioControls);
  452. if (!this.$refs.customTabbar.$refs.audioControls) {
  453. console.error('❌ audioControls引用不存在');
  454. uni.showToast({
  455. title: '音频控制组件未准备好',
  456. icon: 'none'
  457. });
  458. return;
  459. }
  460. // 检查当前页面是否为文本页面或卡片页面
  461. // 卡片页面(type为'1')现在也支持整句音频播放
  462. // 特别针对划线重点页面的调试
  463. if (this.currentPageType === '1') {
  464. }
  465. if (!this.isTextPage && this.currentPageType !== '1') {
  466. console.warn('⚠️ 当前页面不是文本页面或卡片页面');
  467. uni.showToast({
  468. title: '当前页面不支持音频播放',
  469. icon: 'none'
  470. });
  471. return;
  472. }
  473. // 获取音频控制组件实例
  474. const audioControls = this.$refs.customTabbar.$refs.audioControls;
  475. // 检查音频是否正在加载中
  476. if (audioControls.isAudioLoading) {
  477. uni.showToast({
  478. title: '音频正在加载中,请稍后再试',
  479. icon: 'loading',
  480. duration: 1500
  481. });
  482. // 等待音频加载完成后自动播放
  483. const checkAndPlay = () => {
  484. if (!audioControls.isAudioLoading && audioControls.currentPageAudios.length > 0) {
  485. const success = audioControls.playSpecificAudio(textContent);
  486. if (!success) {
  487. console.error('❌ 音频加载完成后播放失败');
  488. }
  489. } else if (!audioControls.isAudioLoading) {
  490. console.error('❌ 音频加载完成但没有音频数据');
  491. uni.showToast({
  492. title: '当前页面没有音频内容',
  493. icon: 'none'
  494. });
  495. } else {
  496. // 继续等待
  497. setTimeout(checkAndPlay, 500);
  498. }
  499. };
  500. // 延迟检查,给音频加载一些时间
  501. setTimeout(checkAndPlay, 1000);
  502. return;
  503. }
  504. // 检查是否有音频数据
  505. if (!audioControls.currentPageAudios || audioControls.currentPageAudios.length === 0) {
  506. console.warn('⚠️ 当前页面没有音频数据,尝试重新加载');
  507. uni.showToast({
  508. title: '正在重新加载音频...',
  509. icon: 'loading'
  510. });
  511. // 尝试重新加载音频
  512. audioControls.getCurrentPageAudio();
  513. // 等待重新加载完成后播放
  514. const retryPlay = () => {
  515. if (!audioControls.isAudioLoading && audioControls.currentPageAudios.length > 0) {
  516. const success = audioControls.playSpecificAudio(textContent);
  517. if (!success) {
  518. console.error('❌ 音频重新加载后播放失败');
  519. }
  520. } else if (!audioControls.isAudioLoading) {
  521. console.error('❌ 音频重新加载失败');
  522. uni.showToast({
  523. title: '音频加载失败,请检查网络连接',
  524. icon: 'none'
  525. });
  526. } else {
  527. // 继续等待
  528. setTimeout(retryPlay, 500);
  529. }
  530. };
  531. setTimeout(retryPlay, 1500);
  532. return;
  533. }
  534. // 调用AudioControls组件的播放指定音频方法
  535. const success = audioControls.playSpecificAudio(textContent);
  536. // console.log('🎵 playSpecificAudio 返回结果:', success);
  537. if (success) {
  538. // console.log('✅ 成功播放指定音频段落');
  539. } else {
  540. console.error('❌ 播放指定音频段落失败');
  541. // console.log('💡 失败可能原因:');
  542. // console.log(' 1. 文本内容与音频数据不匹配');
  543. // console.log(' 2. 音频数据尚未加载完成');
  544. // console.log(' 3. 音频文件路径错误或文件损坏');
  545. // console.log(' 4. 网络连接问题');
  546. }
  547. // console.log('🎯 ===== 文本点击事件结束 =====');
  548. },
  549. onHighlightChange(highlightData) {
  550. // 兼容旧格式(直接传递索引)和新格式(传递对象)
  551. if (typeof highlightData === 'number') {
  552. // 旧格式:直接是索引
  553. this.currentHighlightIndex = highlightData;
  554. } else if (typeof highlightData === 'object' && highlightData !== null) {
  555. // 新格式:包含详细信息的对象
  556. this.currentHighlightIndex = highlightData.highlightIndex;
  557. // 可以在这里处理分段音频的额外信息
  558. if (highlightData.isSegmented) {
  559. // console.log('分段音频高亮:', {
  560. // highlightIndex: highlightData.highlightIndex,
  561. // segmentIndex: highlightData.segmentIndex,
  562. // startIndex: highlightData.startIndex,
  563. // endIndex: highlightData.endIndex,
  564. // currentText: highlightData.currentText
  565. // });
  566. }
  567. } else {
  568. // 清除高亮
  569. this.currentHighlightIndex = -1;
  570. }
  571. },
  572. // 获取音色列表 拿第一个做默认的音色id
  573. async getVoiceList() {
  574. const voiceRes = await this.$api.music.list()
  575. if(voiceRes.code === 200){
  576. // console.log('音色列表API返回:', voiceRes.result);
  577. // console.log('第一个音色数据:', voiceRes.result[0]);
  578. this.voiceId = Number(voiceRes.result[0].voiceType)
  579. // console.log('获取默认音色ID:', this.voiceId, '类型:', typeof this.voiceId);
  580. }
  581. },
  582. toggleNavbar() {
  583. this.showNavbar = !this.showNavbar
  584. },
  585. goBack() {
  586. uni.navigateBack()
  587. },
  588. toggleCoursePopup() {
  589. if (this.$refs.coursePopup) {
  590. this.$refs.coursePopup.open()
  591. }
  592. // console.log('123123123');
  593. },
  594. toggleSort() {
  595. this.isReversed = !this.isReversed
  596. },
  597. selectCourse(courseId) {
  598. this.currentCourse = courseId
  599. // 这里可以添加切换课程的逻辑
  600. // console.log('选择课程:', courseId)
  601. this.getCourseList(courseId)
  602. },
  603. showWordMeaning() {
  604. if (this.$refs.meaningPopup) {
  605. this.$refs.meaningPopup.open()
  606. }
  607. },
  608. closeMeaningPopup() {
  609. this.currentWordMeaning = null;
  610. // 重置音频播放状态,确保后续句子点击能正常播放
  611. if (this.isWordAudioPlaying) {
  612. this.isWordAudioPlaying = false;
  613. // 如果有正在播放的音频,停止它
  614. if (this.currentWordAudio) {
  615. try {
  616. this.currentWordAudio.pause();
  617. this.currentWordAudio.destroy();
  618. } catch (error) {
  619. }
  620. this.currentWordAudio = null;
  621. }
  622. }
  623. },
  624. // 将英文句子分割成单词数组
  625. splitEnglishSentence(sentence) {
  626. // 使用正则表达式分割句子,保留标点符号
  627. const tokens = sentence.match(/\b\w+\b|[^\w\s]/g) || [];
  628. return tokens.map((token, index) => ({
  629. text: token,
  630. index: index,
  631. isWord: /\b\w+\b/.test(token), // 判断是否为单词
  632. hasDefinition: false // 是否有释义,稍后会设置
  633. }));
  634. },
  635. // 查找单词释义
  636. findWordDefinition(word) {
  637. const currentPageWords = this.pageWords[this.currentPage - 1] || [];
  638. // 不区分大小写匹配
  639. return currentPageWords.find(wordData =>
  640. wordData.word.toLowerCase() === word.toLowerCase()
  641. );
  642. },
  643. // 处理中文文本,标记重点词汇
  644. processChineseText(text) {
  645. const currentPageWords = this.pageWords[this.currentPage - 1] || [];
  646. if (!text || currentPageWords.length === 0) {
  647. return [{ text: text, isKeyword: false, keywordData: null }];
  648. }
  649. // 创建一个数组来存储处理后的文本片段
  650. const segments = [];
  651. let currentIndex = 0;
  652. // 按照重点词汇的长度排序,优先匹配较长的词汇
  653. const sortedWords = [...currentPageWords].sort((a, b) => b.word.length - a.word.length);
  654. while (currentIndex < text.length) {
  655. let matched = false;
  656. // 尝试匹配重点词汇
  657. for (const wordData of sortedWords) {
  658. const keyword = wordData.word;
  659. if (text.substr(currentIndex, keyword.length) === keyword) {
  660. // 找到匹配的重点词汇
  661. segments.push({
  662. text: keyword,
  663. isKeyword: true,
  664. keywordData: wordData
  665. });
  666. currentIndex += keyword.length;
  667. matched = true;
  668. break;
  669. }
  670. }
  671. if (!matched) {
  672. // 没有匹配到重点词汇,添加单个字符
  673. segments.push({
  674. text: text[currentIndex],
  675. isKeyword: false,
  676. keywordData: null
  677. });
  678. currentIndex++;
  679. }
  680. }
  681. // 合并相邻的非重点词汇片段
  682. const mergedSegments = [];
  683. let currentSegment = null;
  684. for (const segment of segments) {
  685. if (segment.isKeyword) {
  686. // 如果当前有未完成的非重点词汇片段,先添加它
  687. if (currentSegment) {
  688. mergedSegments.push(currentSegment);
  689. currentSegment = null;
  690. }
  691. // 添加重点词汇
  692. mergedSegments.push(segment);
  693. } else {
  694. // 非重点词汇,合并到当前片段
  695. if (currentSegment) {
  696. currentSegment.text += segment.text;
  697. } else {
  698. currentSegment = { ...segment };
  699. }
  700. }
  701. }
  702. // 添加最后的非重点词汇片段
  703. if (currentSegment) {
  704. mergedSegments.push(currentSegment);
  705. }
  706. return mergedSegments;
  707. },
  708. async playWordAudio(word) {
  709. try {
  710. // 检查是否有音频正在播放,如果有则停止
  711. if (this.isWordAudioPlaying) {
  712. this.isWordAudioPlaying = false;
  713. }
  714. // 🎯 全局音频管理:停止主音频播放,确保只有一个音频播放
  715. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  716. const audioControls = this.$refs.customTabbar.$refs.audioControls;
  717. if (audioControls.isPlaying) {
  718. audioControls.pauseAudio();
  719. }
  720. }
  721. // 停止當前播放的單詞語音
  722. if (this.currentWordAudio) {
  723. try {
  724. // 先暂停,再销毁,确保清理完整
  725. this.currentWordAudio.pause();
  726. this.currentWordAudio.destroy();
  727. } catch (error) {
  728. }
  729. this.currentWordAudio = null;
  730. this.isWordAudioPlaying = false;
  731. } else {
  732. }
  733. // 🎯 确保音色ID已加载完成后再获取音频
  734. if (!this.voiceId || this.voiceId === '' || this.voiceId === null || this.voiceId === undefined) {
  735. uni.showToast({
  736. title: '音色未加载,请稍后重试',
  737. icon: 'none',
  738. duration: 2000
  739. });
  740. return;
  741. }
  742. // 調用語音轉換API
  743. const audioRes = await this.$api.music.textToVoice({
  744. text: word,
  745. voiceType: this.voiceId
  746. });
  747. // 檢查響應並播放音頻
  748. if (audioRes && audioRes.result && audioRes.result.url) {
  749. // 新格式:使用返回的url字段
  750. const audioUrl = audioRes.result.url;
  751. // 創建並播放音頻
  752. const audio = uni.createInnerAudioContext();
  753. audio.src = audioUrl;
  754. // 添加音频加载完成监听器
  755. audio.onCanplay(() => {
  756. });
  757. audio.onPlay(() => {
  758. this.isWordAudioPlaying = true;
  759. });
  760. audio.onEnded(() => {
  761. this.isWordAudioPlaying = false;
  762. audio.destroy();
  763. if (this.currentWordAudio === audio) {
  764. this.currentWordAudio = null;
  765. } else {
  766. }
  767. });
  768. audio.onError((error) => {
  769. console.error('❌ 音频播放失败:', error);
  770. this.isWordAudioPlaying = false;
  771. console.log('🔄 播放状态已重置为 false (错误)');
  772. try {
  773. audio.destroy();
  774. } catch (destroyError) {
  775. console.error('⚠️ 销毁音频实例时出错:', destroyError);
  776. }
  777. if (this.currentWordAudio === audio) {
  778. this.currentWordAudio = null;
  779. console.log('🔄 currentWordAudio 已重置为 null (错误)');
  780. } else {
  781. }
  782. uni.showToast({
  783. title: '語音播放失敗',
  784. icon: 'none'
  785. });
  786. });
  787. // 保存當前音頻實例並播放
  788. this.currentWordAudio = audio;
  789. // 添加一个小延迟确保音频实例完全准备好
  790. setTimeout(() => {
  791. if (this.currentWordAudio === audio) {
  792. try {
  793. audio.play();
  794. } catch (playError) {
  795. console.error('❌ 播放命令失败:', playError);
  796. uni.showToast({
  797. title: '音频播放失败',
  798. icon: 'none'
  799. });
  800. }
  801. } else {
  802. }
  803. }, 100);
  804. } else {
  805. console.error('❌ API响应无效:', audioRes);
  806. uni.showToast({
  807. title: '語音播放失敗',
  808. icon: 'none'
  809. });
  810. }
  811. } catch (error) {
  812. console.error('❌ 播放单词语音异常:', error);
  813. uni.showToast({
  814. title: '語音播放失敗',
  815. icon: 'none'
  816. });
  817. }
  818. },
  819. // 重複播放單詞語音(用於釋義彈窗中的揚聲器圖標)
  820. repeatWordAudio() {
  821. if (this.currentWordMeaning && this.currentWordMeaning.word) {
  822. // 将单词和解释合并后播放音频
  823. const combinedText = `${this.currentWordMeaning.word}${this.currentWordMeaning.meaning || ''}`;
  824. this.playWordAudio(combinedText);
  825. } else {
  826. console.warn('沒有當前單詞可以播放');
  827. }
  828. },
  829. // 处理单词点击事件
  830. handleWordClick(word) {
  831. const definition = this.findWordDefinition(word);
  832. if (definition) {
  833. this.currentWordMeaning = {
  834. word: definition.word,
  835. phonetic: definition.soundmark || '',
  836. partOfSpeech: '', // 可以根据需要添加词性
  837. meaning: definition.paraphrase || '',
  838. knowledgeGain: definition.knowledge || '',
  839. image: definition.image || ''
  840. };
  841. // 将单词和解释合并后播放音频
  842. const combinedText = `${word}${definition.paraphrase || ''}`;
  843. this.playWordAudio(combinedText);
  844. this.showWordMeaning();
  845. } else {
  846. // 如果没有释义,只播放单词
  847. if (word) {
  848. this.playWordAudio(word);
  849. } else {
  850. }
  851. }
  852. },
  853. // 处理中文重点词汇点击事件
  854. handleChineseKeywordClick(keywordData) {
  855. if (keywordData) {
  856. this.currentWordMeaning = {
  857. word: keywordData.word,
  858. phonetic: keywordData.soundmark || '',
  859. partOfSpeech: '', // 可以根据需要添加词性
  860. meaning: keywordData.paraphrase || '',
  861. knowledgeGain: keywordData.knowledge || ''
  862. };
  863. // 将词汇和解释合并后播放音频
  864. const combinedText = `${keywordData.word}${keywordData.paraphrase || ''}`;
  865. this.playWordAudio(combinedText);
  866. this.showWordMeaning();
  867. } else {
  868. }
  869. },
  870. // 计算音频总时长
  871. async calculateTotalDuration() {
  872. let totalDuration = 0;
  873. for (let i = 0; i < this.currentPageAudios.length; i++) {
  874. const audio = this.currentPageAudios[i];
  875. // 優先使用API返回的時長信息
  876. if (audio.duration && audio.duration > 0) {
  877. totalDuration += audio.duration;
  878. continue;
  879. }
  880. // 如果沒有API時長信息,嘗試獲取音頻時長
  881. try {
  882. const duration = await this.getAudioDuration(audio.url);
  883. audio.duration = duration;
  884. totalDuration += duration;
  885. } catch (error) {
  886. console.error('获取音频时长失败:', error);
  887. // 如果无法获取时长,根據文字長度估算(更精確的估算)
  888. const textLength = audio.text.length;
  889. // 假設每分鐘可以讀150-200個字符,這裡用180作為平均值
  890. const estimatedDuration = Math.max(2, textLength / 3); // 每3個字符約1秒
  891. audio.duration = estimatedDuration;
  892. totalDuration += estimatedDuration;
  893. console.log(`估算音頻時長 ${i + 1}:`, estimatedDuration, '秒 (文字長度:', textLength, ')');
  894. }
  895. }
  896. this.totalTime = totalDuration;
  897. },
  898. // 获取音频时长
  899. getAudioDuration(audioUrl) {
  900. return new Promise((resolve, reject) => {
  901. const audio = uni.createInnerAudioContext();
  902. audio.src = audioUrl;
  903. let resolved = false;
  904. // 监听音频加载完成事件
  905. audio.onCanplay(() => {
  906. if (!resolved && audio.duration && audio.duration > 0) {
  907. resolved = true;
  908. resolve(audio.duration);
  909. audio.destroy();
  910. }
  911. });
  912. // 监听音频元数据加载完成事件
  913. audio.onLoadedmetadata = () => {
  914. if (!resolved && audio.duration && audio.duration > 0) {
  915. resolved = true;
  916. resolve(audio.duration);
  917. audio.destroy();
  918. }
  919. };
  920. // 监听音频时长更新事件
  921. audio.onDurationChange = () => {
  922. if (!resolved && audio.duration && audio.duration > 0) {
  923. resolved = true;
  924. resolve(audio.duration);
  925. audio.destroy();
  926. }
  927. };
  928. // 如果以上方法都無法獲取時長,嘗試播放一小段來獲取時長
  929. audio.onPlay(() => {
  930. if (!resolved) {
  931. setTimeout(() => {
  932. if (!resolved && audio.duration && audio.duration > 0) {
  933. resolved = true;
  934. resolve(audio.duration);
  935. audio.destroy();
  936. }
  937. }, 100); // 播放100ms後檢查時長
  938. }
  939. });
  940. audio.onError((error) => {
  941. console.error('音频加载失败:', error);
  942. if (!resolved) {
  943. resolved = true;
  944. reject(error);
  945. audio.destroy();
  946. }
  947. });
  948. // 設置較長的超時時間,並在超時前嘗試播放
  949. setTimeout(() => {
  950. if (!resolved) {
  951. audio.play();
  952. }
  953. }, 1000);
  954. // 最終超時處理
  955. setTimeout(() => {
  956. if (!resolved) {
  957. console.warn('獲取音頻時長超時,使用默認值');
  958. resolved = true;
  959. reject(new Error('获取音频时长超时'));
  960. audio.destroy();
  961. }
  962. }, 5000);
  963. });
  964. },
  965. // 音频控制方法 - 这些方法现在由AudioControls组件处理
  966. // 保留一些简单的接口方法用于与AudioControls组件通信
  967. // 判断当前文本是否应该高亮 - 这个方法需要保留,因为它用于模板渲染
  968. isTextHighlighted(page, index) {
  969. // 只有当前页面且是文本类型才可能高亮
  970. if (page !== this.bookPages[this.currentPage - 1]) return false;
  971. // 计算当前页面中text类型元素的索引
  972. let textIndex = 0;
  973. for (let i = 0; i <= index; i++) {
  974. if (page[i].type === 'text') {
  975. if (i === index) {
  976. const shouldHighlight = textIndex === this.currentHighlightIndex;
  977. if (shouldHighlight) {
  978. }
  979. return shouldHighlight;
  980. }
  981. textIndex++;
  982. }
  983. }
  984. return false;
  985. },
  986. async previousPage() {
  987. if (this.currentPage > 1) {
  988. this.currentPage--;
  989. // 获取对应页面的数据(如果还没有获取过)
  990. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  991. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  992. }
  993. }
  994. },
  995. async nextPage() {
  996. if (this.currentPage < this.bookPages.length) {
  997. this.currentPage++;
  998. // 获取对应页面的数据(如果还没有获取过)
  999. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1000. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1001. }
  1002. }
  1003. },
  1004. toggleSound() {
  1005. // 检查是否正在加载音频,如果是则阻止音色切换
  1006. if (this.isAudioLoading) {
  1007. uni.showToast({
  1008. title: '音频加载中,请稍后再试',
  1009. icon: 'none',
  1010. duration: 2000
  1011. });
  1012. return;
  1013. }
  1014. // 检查AudioControls组件是否正在加载音频
  1015. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls && this.$refs.customTabbar.$refs.audioControls.isAudioLoading) {
  1016. uni.showToast({
  1017. title: '音频加载中,请稍后再试',
  1018. icon: 'none',
  1019. duration: 2000
  1020. });
  1021. return;
  1022. }
  1023. console.log('音色切换')
  1024. uni.navigateTo({
  1025. url: '/subPages/home/music?voiceId=' + this.voiceId
  1026. })
  1027. },
  1028. unlockBook() {
  1029. console.log('解锁全书')
  1030. // 这里可以跳转到会员页面或者调用解锁接口
  1031. uni.navigateTo({
  1032. url: '/subPages/member/recharge'
  1033. })
  1034. },
  1035. async goToPage(page) {
  1036. this.currentPage = page
  1037. console.log('跳转到页面:', page)
  1038. // 获取对应页面的数据(如果还没有获取过)
  1039. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1040. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1041. }
  1042. },
  1043. async onSwiperChange(e) {
  1044. this.currentPage = e.detail.current + 1
  1045. // 获取对应页面的数据(如果还没有获取过)
  1046. if (this.courseIdList[this.currentPage - 1] && this.bookPages[this.currentPage - 1].length === 0) {
  1047. await this.getBookPages(this.courseIdList[this.currentPage - 1]);
  1048. }
  1049. },
  1050. async getCourseList(id) {
  1051. const res = await this.$api.book.coursePage({
  1052. id: id
  1053. })
  1054. if (res.code === 200) {
  1055. // 课程切换时,先清理音频控制组件的所有数据
  1056. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1057. this.$refs.customTabbar.$refs.audioControls.resetForCourseChange();
  1058. }
  1059. // 清空当前页面相关数据
  1060. this.currentPage = 1; // 重置到第一页
  1061. this.currentCourse = 1; // 重置当前课程索引
  1062. this.currentWordMeaning = null; // 清空单词释义
  1063. this.currentWordAudio = null; // 清空单词音频
  1064. this.currentHighlightIndex = -1; // 清空高亮索引
  1065. // 清理单词音频缓存
  1066. this.clearWordAudioCache();
  1067. // 重新初始化课程数据
  1068. this.courseIdList = res.result.map(item => item.id)
  1069. // 初始化二维数组 换一种方式
  1070. this.bookPages = this.courseIdList.map(() => [])
  1071. // 初始化标题数组
  1072. this.pageTitles = this.courseIdList.map(() => '')
  1073. // 初始化页面类型数组
  1074. this.pageTypes = this.courseIdList.map(() => '')
  1075. // 初始化页面单词数组
  1076. this.pageWords = this.courseIdList.map(() => [])
  1077. // 初始化滚动位置数组
  1078. this.scrollTops = this.courseIdList.map(() => 0)
  1079. // 初始化第一页
  1080. if (this.courseIdList.length > 0) {
  1081. await this.getBookPages(this.courseIdList[0])
  1082. // 课程切换后,确保音频控件能正确加载新课程的音频
  1083. // 使用$nextTick确保DOM和数据都已更新
  1084. this.$nextTick(async () => {
  1085. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1086. try {
  1087. // 直接调用getCurrentPageAudio方法,更可靠
  1088. await this.$refs.customTabbar.$refs.audioControls.getCurrentPageAudio();
  1089. } catch (error) {
  1090. console.error('课程切换后音频加载失败:', error);
  1091. }
  1092. }
  1093. });
  1094. // 预加载后续几页的内容(异步执行,不阻塞当前页面显示)
  1095. this.preloadNextPages()
  1096. }
  1097. }
  1098. },
  1099. async getBookPages(id) {
  1100. const res = await this.$api.book.coursesPageDetail({
  1101. id: id
  1102. })
  1103. if (res.code === 200) {
  1104. // 使用$set确保响应式更新
  1105. const rawPageData = JSON.parse(res.result.content)
  1106. console.log('获取到的原始页面数据:', rawPageData)
  1107. // 过滤掉无效的数据项
  1108. const filteredPageData = rawPageData.filter(item => {
  1109. return item && typeof item === 'object' && (item.type || item.content)
  1110. })
  1111. console.log('过滤后的页面数据:', filteredPageData)
  1112. // 确保当前页面存在
  1113. if (this.currentPage - 1 < this.bookPages.length) {
  1114. this.$set(this.bookPages, this.currentPage - 1, filteredPageData)
  1115. // 保存页面标题
  1116. this.$set(this.pageTitles, this.currentPage - 1, res.result.title || '')
  1117. // 保存页面类型
  1118. this.$set(this.pageTypes, this.currentPage - 1, res.result.type || '')
  1119. // 保存页面单词释义数据
  1120. this.$set(this.pageWords, this.currentPage - 1, res.result.words || [])
  1121. // 保存页面付费状态
  1122. this.$set(this.pagePay, this.currentPage - 1, res.result.pay || 'N')
  1123. }
  1124. }
  1125. },
  1126. // 获取课程列表
  1127. async getCoursePageList (bookId) {
  1128. const res = await this.$api.book.course({
  1129. id: bookId
  1130. })
  1131. if (res.code === 200) {
  1132. this.courseList = res.result.records
  1133. // 打上序列号
  1134. this.courseList = this.courseList.map((item, index) => ({
  1135. ...item,
  1136. index,
  1137. }))
  1138. }
  1139. },
  1140. // 清理音频缓存
  1141. clearAudioCache() {
  1142. this.audioCache = {};
  1143. },
  1144. // 清理單詞語音緩存
  1145. clearWordAudioCache() {
  1146. this.wordAudioCache = {};
  1147. },
  1148. // 限制缓存大小,保留最近访问的页面
  1149. limitCacheSize(maxSize = 10) {
  1150. const cacheKeys = Object.keys(this.audioCache);
  1151. if (cacheKeys.length > maxSize) {
  1152. // 删除最旧的缓存项
  1153. const keysToDelete = cacheKeys.slice(0, cacheKeys.length - maxSize);
  1154. keysToDelete.forEach(key => {
  1155. delete this.audioCache[key];
  1156. });
  1157. }
  1158. },
  1159. // 预加载后续页面内容
  1160. async preloadNextPages() {
  1161. try {
  1162. // 优化策略:只预加载接下来的2-3页内容,避免过多请求
  1163. const preloadCount = Math.min(3, this.courseIdList.length - 1); // 预加载3页或剩余页数
  1164. // 串行预加载,避免并发请求过多
  1165. for (let i = 1; i <= preloadCount; i++) {
  1166. if (i < this.courseIdList.length && this.bookPages[i].length === 0) {
  1167. try {
  1168. await this.preloadSinglePage(this.courseIdList[i], i);
  1169. // 每页之间间隔800ms,给服务器更多缓冲时间
  1170. if (i < preloadCount) {
  1171. await new Promise(resolve => setTimeout(resolve, 800));
  1172. }
  1173. } catch (error) {
  1174. console.error(`预加载第${i + 1}页失败:`, error);
  1175. // 继续预加载下一页
  1176. }
  1177. }
  1178. }
  1179. // 延迟1.5秒后再通知AudioControls组件开始预加载音频,避免接口冲突
  1180. setTimeout(() => {
  1181. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1182. this.$refs.customTabbar.$refs.audioControls.startPreloadAudio();
  1183. }
  1184. }, 1500);
  1185. } catch (error) {
  1186. console.error('预加载页面内容失败:', error);
  1187. }
  1188. },
  1189. // 预加载单个页面
  1190. async preloadSinglePage(courseId, pageIndex) {
  1191. try {
  1192. const res = await this.$api.book.coursesPageDetail({
  1193. id: courseId
  1194. });
  1195. if (res.code === 200) {
  1196. const rawPageData = JSON.parse(res.result.content);
  1197. const filteredPageData = rawPageData.filter(item => {
  1198. return item && typeof item === 'object' && (item.type || item.content);
  1199. });
  1200. // 使用$set确保响应式更新
  1201. this.$set(this.bookPages, pageIndex, filteredPageData);
  1202. this.$set(this.pageTitles, pageIndex, res.result.title || '');
  1203. this.$set(this.pageTypes, pageIndex, res.result.type || '');
  1204. this.$set(this.pageWords, pageIndex, res.result.words || []);
  1205. this.$set(this.pagePay, pageIndex, res.result.pay || 'N');
  1206. }
  1207. } catch (error) {
  1208. console.error(`预加载第${pageIndex + 1}页失败:`, error);
  1209. throw error;
  1210. }
  1211. },
  1212. // 自動加載第一頁音頻並播放
  1213. async autoLoadAndPlayFirstPage() {
  1214. try {
  1215. // 確保當前是第一頁且需要加載音頻
  1216. if (this.currentPage === 1 && this.shouldLoadAudio) {
  1217. // 加載音頻
  1218. await this.getCurrentPageAudio();
  1219. // 檢查是否成功加載音頻
  1220. if (this.currentPageAudios && this.currentPageAudios.length > 0) {
  1221. // getCurrentPageAudio方法已經處理了第一個音頻的播放,這裡不需要再次調用playAudio
  1222. } else {
  1223. }
  1224. } else {
  1225. }
  1226. } catch (error) {
  1227. console.error('自動加載和播放音頻失敗:', error);
  1228. }
  1229. },
  1230. },
  1231. async onLoad(args) {
  1232. this.$scrollTo('imageRef')
  1233. // 监听音色切换事件,传递给AudioControls组件处理
  1234. uni.$on('selectVoice', async (voiceId) => {
  1235. if (this.voiceId === voiceId) {
  1236. return;
  1237. }
  1238. // 检查是否正在加载音频,如果是则阻止音色切换
  1239. if (this.isAudioLoading || (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls && this.$refs.customTabbar.$refs.audioControls.isAudioLoading)) {
  1240. uni.showToast({
  1241. title: '音频加载中,请稍后再试',
  1242. icon: 'none',
  1243. duration: 2000
  1244. });
  1245. return;
  1246. }
  1247. // 更新本地音色ID
  1248. this.voiceId = voiceId;
  1249. // 清理單詞語音資源
  1250. this.clearWordAudioCache();
  1251. if (this.currentWordAudio) {
  1252. this.currentWordAudio.destroy();
  1253. this.currentWordAudio = null;
  1254. }
  1255. // 通知AudioControls组件处理音色切换
  1256. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1257. try {
  1258. // 传入选项:preloadAllPages: true 表示要预加载所有页面的音频
  1259. await this.$refs.customTabbar.$refs.audioControls.handleVoiceChange(voiceId, {
  1260. preloadAllPages: true
  1261. });
  1262. } catch (error) {
  1263. console.error('音色切换处理失败:', error);
  1264. }
  1265. }
  1266. })
  1267. this.courseId = args.courseId
  1268. this.memberId = args.memberId
  1269. // 先获取点进来的课程的页面列表
  1270. await Promise.all([this.getVoiceList(),this.getMemberInfo(),this.getCourseList(this.courseId), this.getCoursePageList(args.bookId)])
  1271. // 页面加载完成后,通知AudioControls组件自动加载第一页音频
  1272. this.$nextTick(() => {
  1273. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1274. this.$refs.customTabbar.$refs.audioControls.autoLoadAndPlayFirstPage();
  1275. }
  1276. });
  1277. },
  1278. // 页面卸载时清理资源
  1279. onUnload() {
  1280. uni.$off('selectVoice')
  1281. // 1. 清理单词语音资源
  1282. if (this.currentWordAudio) {
  1283. try {
  1284. this.currentWordAudio.destroy();
  1285. } catch (error) {
  1286. console.error('销毁单词音频实例失败:', error);
  1287. }
  1288. this.currentWordAudio = null;
  1289. }
  1290. // 2. 清理单词语音缓存
  1291. this.clearWordAudioCache();
  1292. // 3. 停止单词音频播放状态
  1293. this.isWordAudioPlaying = false;
  1294. // 4. 通知AudioControls组件清理资源
  1295. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1296. this.$refs.customTabbar.$refs.audioControls.destroyAudio();
  1297. }
  1298. // 5. 清理全局音频实例(防止遗漏)
  1299. try {
  1300. // 获取所有可能的音频上下文并销毁
  1301. if (typeof wx !== 'undefined' && wx.getBackgroundAudioManager) {
  1302. const bgAudio = wx.getBackgroundAudioManager();
  1303. if (bgAudio) {
  1304. bgAudio.stop();
  1305. }
  1306. }
  1307. } catch (error) {
  1308. console.error('清理背景音频失败:', error);
  1309. }
  1310. },
  1311. // 页面隐藏时暂停音频
  1312. onHide() {
  1313. // 1. 暂停单词音频
  1314. if (this.currentWordAudio && this.isWordAudioPlaying) {
  1315. try {
  1316. this.currentWordAudio.pause();
  1317. this.isWordAudioPlaying = false;
  1318. } catch (error) {
  1319. console.error('暂停单词音频失败:', error);
  1320. }
  1321. }
  1322. // 2. 通知AudioControls组件暂停音频
  1323. if (this.$refs.customTabbar && this.$refs.customTabbar.$refs.audioControls) {
  1324. this.$refs.customTabbar.$refs.audioControls.pauseOnHide();
  1325. }
  1326. }
  1327. }
  1328. </script>
  1329. <style lang="scss" scoped>
  1330. .book-container {
  1331. width: 100%;
  1332. min-height: 100vh;
  1333. background-color: #F8F8F8;
  1334. position: relative;
  1335. overflow: hidden;
  1336. }
  1337. .custom-navbar {
  1338. position: fixed;
  1339. top: 0;
  1340. left: 0;
  1341. right: 0;
  1342. background-color: #F8F8F8;
  1343. z-index: 1000;
  1344. transition: transform 0.3s ease;
  1345. &.navbar-hidden {
  1346. transform: translateY(-100%);
  1347. }
  1348. }
  1349. .navbar-content {
  1350. display: flex;
  1351. align-items: center;
  1352. justify-content: space-between;
  1353. padding: 20rpx 32rpx;
  1354. // padding-top: calc(20rpx + var(--status-bar-height, 0));
  1355. height: 60rpx;
  1356. }
  1357. .navbar-left,
  1358. .navbar-right {
  1359. width: 80rpx;
  1360. display: flex;
  1361. align-items: center;
  1362. }
  1363. .navbar-right {
  1364. justify-content: flex-end;
  1365. flex: 1;
  1366. }
  1367. .navbar-title {
  1368. transform: translateX(-50rpx);
  1369. flex: 1;
  1370. text-align: center;
  1371. font-family: PingFang SC;
  1372. font-weight: 500;
  1373. font-size: 32rpx;
  1374. color: #262626;
  1375. line-height: 48rpx;
  1376. }
  1377. .content-swiper {
  1378. flex: 1;
  1379. // min-height: calc(100vh - 100rpx);
  1380. // margin-top: 100rpx;
  1381. height: 100vh;
  1382. }
  1383. .swiper-item {
  1384. min-height: 100vh;
  1385. // background-color: red;
  1386. }
  1387. .content-area {
  1388. flex: 1;
  1389. padding: 30rpx 40rpx 100rpx;
  1390. /* #ifndef H5 */
  1391. padding: 100rpx 40rpx;
  1392. /* #endif */
  1393. // padding-top: ;
  1394. // background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);
  1395. min-height: 100%;
  1396. box-sizing: border-box;
  1397. overflow-y: auto;
  1398. .title{
  1399. font-family: PingFang SC;
  1400. font-weight: 500;
  1401. font-size: 34rpx;
  1402. text-align: center;
  1403. color: #181818;
  1404. line-height: 48rpx;
  1405. margin-bottom: 32rpx;
  1406. }
  1407. .image-container {
  1408. width: 100%;
  1409. display: flex;
  1410. justify-content: center;
  1411. align-items: center;
  1412. margin: 30rpx 0;
  1413. /* 平板设备适配 */
  1414. @media screen and (min-width: 768px) {
  1415. margin: 40rpx 0;
  1416. }
  1417. }
  1418. .content-image{
  1419. width: 100%;
  1420. height: auto;
  1421. max-width: 600rpx; /* 限制最大宽度,避免在大屏设备上过大 */
  1422. display: block;
  1423. border-radius: 12rpx; /* 添加圆角,提升视觉效果 */
  1424. box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); /* 添加阴影,增强层次感 */
  1425. /* 平板设备适配 */
  1426. @media screen and (min-width: 768px) {
  1427. max-width: 500rpx;
  1428. }
  1429. }
  1430. .video-content{
  1431. width: 100%;
  1432. height: auto;
  1433. margin: 30rpx auto;
  1434. position: relative;
  1435. .video-player{
  1436. // height: 100%;
  1437. width: 100%;
  1438. // margin: 0 auto;
  1439. // height: auto;
  1440. }
  1441. .video-loading {
  1442. position: absolute;
  1443. top: 50%;
  1444. left: 50%;
  1445. transform: translate(-50%, -50%);
  1446. color: #666;
  1447. font-size: 28rpx;
  1448. }
  1449. }
  1450. }
  1451. .card-content {
  1452. background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);
  1453. display: flex;
  1454. flex-direction: column;
  1455. gap: 32rpx;
  1456. min-height: 1172rpx;
  1457. margin-top: 20rpx;
  1458. border-radius: 32rpx;
  1459. // height: 100%;
  1460. padding: 40rpx;
  1461. padding-bottom: 100rpx;
  1462. // margin: 0
  1463. border: 1px solid #FFFFFF;
  1464. box-sizing: border-box;
  1465. .card-line {
  1466. display: flex;
  1467. align-items: center;
  1468. // margin-bottom: 20rpx;
  1469. }
  1470. .card-line-image {
  1471. width: 48rpx;
  1472. height: 48rpx;
  1473. margin-right: 16rpx;
  1474. }
  1475. .card-line-text {
  1476. font-family: PingFang SC;
  1477. font-weight: 600;
  1478. font-size: 30rpx;
  1479. line-height: 48rpx;
  1480. color: #3B3D3D;
  1481. }
  1482. .card-image {
  1483. width: 590rpx;
  1484. height: 268rpx;
  1485. border-radius: 24rpx;
  1486. margin: 30rpx auto;
  1487. // margin-bottom: 20rpx;
  1488. }
  1489. .english-text {
  1490. display: block;
  1491. font-family: PingFang SC;
  1492. font-weight: 600;
  1493. font-size: 32rpx;
  1494. line-height: 48rpx;
  1495. color: #3B3D3D;
  1496. // margin-bottom: 16rpx;
  1497. }
  1498. .english-text-container {
  1499. display: flex;
  1500. flex-wrap: wrap;
  1501. align-items: baseline;
  1502. }
  1503. .english-token {
  1504. font-family: PingFang SC;
  1505. font-weight: 600;
  1506. font-size: 32rpx;
  1507. line-height: 48rpx;
  1508. color: #3B3D3D;
  1509. margin-right: 10rpx;
  1510. }
  1511. .clickable-word {
  1512. background: $primary-color;
  1513. text-decoration: underline;
  1514. cursor: pointer;
  1515. transition: all 0.2s ease;
  1516. }
  1517. .clickable-word:hover {
  1518. background-color: rgba(0, 122, 255, 0.1);
  1519. border-radius: 4rpx;
  1520. }
  1521. .chinese-segment {
  1522. font-family: PingFang SC;
  1523. font-weight: 400;
  1524. font-size: 28rpx;
  1525. line-height: 48rpx;
  1526. color: #3B3D3D;
  1527. }
  1528. .clickable-keyword {
  1529. background: $primary-color;
  1530. text-decoration: underline;
  1531. cursor: pointer;
  1532. transition: all 0.2s ease;
  1533. border-radius: 4rpx;
  1534. padding: 2rpx 4rpx;
  1535. }
  1536. .clickable-keyword:hover {
  1537. background-color: rgba(0, 122, 255, 0.1);
  1538. }
  1539. .chinese-text {
  1540. display: block;
  1541. font-family: PingFang SC;
  1542. font-weight: 400;
  1543. font-size: 28rpx;
  1544. line-height: 48rpx;
  1545. color: #4F4F4F;
  1546. }
  1547. }
  1548. /* 会员限制页面样式 */
  1549. .member-content {
  1550. display: flex;
  1551. flex-direction: column;
  1552. align-items: center;
  1553. justify-content: center;
  1554. height: 90%;
  1555. background-color: #F8F8F8;
  1556. padding: 40rpx;
  1557. margin: -40rpx;
  1558. box-sizing: border-box;
  1559. }
  1560. .member-title {
  1561. font-family: PingFang SC;
  1562. font-weight: 500;
  1563. font-size: 40rpx;
  1564. line-height: 1;
  1565. color: #6f6f6f;
  1566. text-align: center;
  1567. margin-bottom: 48rpx;
  1568. }
  1569. .member-button {
  1570. width: 670rpx;
  1571. height: 72rpx;
  1572. background: #06DADC;
  1573. border-radius: 200rpx;
  1574. display: flex;
  1575. align-items: center;
  1576. justify-content: center;
  1577. }
  1578. .member-button-text {
  1579. font-family: PingFang SC;
  1580. font-weight: 400;
  1581. font-size: 30rpx;
  1582. color: #FFFFFF;
  1583. }
  1584. // .video-content {
  1585. // width: 100%;
  1586. // height: auto;
  1587. // // margin: 200rpx -40rpx 0;
  1588. // // height: 500rpx;
  1589. // background-color: #FFFFFF;
  1590. // // padding: 40rpx;
  1591. // border-radius: 24rpx;
  1592. // display: flex;
  1593. // align-items: center;
  1594. // justify-content: center;
  1595. // .video-player{
  1596. // width: 100%;
  1597. // margin: 0 auto;
  1598. // height: auto;
  1599. // }
  1600. // }
  1601. .text-content {
  1602. width: 100vw;
  1603. background-color: #F6F6F6;
  1604. height: 100%;
  1605. padding: 40rpx;
  1606. margin: -40rpx;
  1607. box-sizing: border-box;
  1608. }
  1609. .content-text {
  1610. font-family: PingFang SC;
  1611. // font-weight: 400;
  1612. font-size: 28rpx;
  1613. color: #3B3D3D;
  1614. line-height: 48rpx;
  1615. letter-spacing: 0;
  1616. text-align: justify;
  1617. word-break: break-all;
  1618. transition: all 0.3s ease;
  1619. }
  1620. .clickable-text {
  1621. cursor: pointer;
  1622. &:active {
  1623. background-color: rgba(6, 218, 220, 0.1);
  1624. border-radius: 4rpx;
  1625. }
  1626. }
  1627. .lead-text {
  1628. background: #fffbe6; /* 柔和的提示背景 */
  1629. border: 1px solid #ffe58f;
  1630. border-radius: 8px;
  1631. padding: 10rpx 20rpx;
  1632. }
  1633. .text-highlight {
  1634. background-color: rgba(255, 248, 220, 0.8); /* 温暖的米黄色,对眼睛友好 */
  1635. border-left: 4rpx solid #ffd700; /* 左侧金色边框作为朗读指示 */
  1636. padding: 4rpx 8rpx;
  1637. border-radius: 6rpx;
  1638. transition: all 0.3s ease;
  1639. box-shadow: 0 2rpx 6rpx rgba(255, 215, 0, 0.15); /* 柔和的阴影 */
  1640. }
  1641. </style>