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

2381 lines
79 KiB

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