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

3275 lines
123 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. <template>
  2. <view class="audio-controls-wrapper">
  3. <!-- 会员限制页面不显示任何音频控制 -->
  4. <view v-if="isAudioDisabled" class="member-restricted-container">
  5. <!-- 不显示任何内容完全隐藏音频功能 -->
  6. </view>
  7. <!-- 音频加载中 -->
  8. <view v-else-if="isTextPage && isAudioLoading" class="audio-loading-container">
  9. <uv-loading-icon mode="spinner" size="30" color="#06DADC"></uv-loading-icon>
  10. <text class="loading-text">{{ currentPage }}页音频加载中请稍等...</text>
  11. </view>
  12. <!-- 正常音频控制栏 -->
  13. <view v-else-if="isTextPage && hasAudioData" class="audio-controls">
  14. <!-- 加载指示器 -->
  15. <view v-if="isAudioLoading" class="loading-indicator">
  16. <uv-loading-icon mode="spinner" size="16" color="#06DADC"></uv-loading-icon>
  17. <text class="loading-indicator-text">正在加载更多音频...</text>
  18. </view>
  19. <!-- <view class="audio-time">
  20. <text class="time-text">{{ formatTime(currentTime) }}</text>
  21. <view class="progress-container">
  22. <uv-slider v-model="sliderValue" :min="0" :max="totalTime" :step="0.1" activeColor="#06DADC"
  23. backgroundColor="#e0e0e0" :blockSize="16" blockColor="#ffffff" disabled
  24. :customStyle="{ flex: 1, margin: '0 10px' }" />
  25. </view>
  26. <text class="time-text">{{ formatTime(totalTime) }}</text>
  27. </view> -->
  28. <view class="audio-controls-row">
  29. <view class="control-btn" @click="toggleLoop">
  30. <uv-icon name="reload" size="20" :color="isLoop ? '#06DADC' : '#999'"></uv-icon>
  31. <text class="control-text">循环</text>
  32. </view>
  33. <view class="control-btn" @click="$emit('previous-page')">
  34. <text class="control-text">上一页</text>
  35. </view>
  36. <view class="play-btn" @click="togglePlay">
  37. <uv-icon :name="isPlaying ? 'pause-circle-fill' : 'play-circle-fill'" size="40"
  38. color="#666"></uv-icon>
  39. </view>
  40. <view class="control-btn" @click="$emit('next-page')">
  41. <text class="control-text">下一页</text>
  42. </view>
  43. <view class="control-btn" @click="toggleSpeed" :class="{ 'disabled': !playbackRateSupported }">
  44. <text class="control-text" :style="{ opacity: playbackRateSupported ? 1 : 0.5 }">
  45. {{ playbackRateSupported ? playSpeed + 'x' : '不支持' }}
  46. </text>
  47. </view>
  48. </view>
  49. </view>
  50. </view>
  51. </template>
  52. <script>
  53. import config from '@/mixins/config.js'
  54. import audioManager from '@/utils/audioManager.js'
  55. export default {
  56. name: 'AudioControls',
  57. mixins: [config],
  58. props: {
  59. // 基础数据
  60. currentPage: {
  61. type: Number,
  62. default: 1
  63. },
  64. courseId: {
  65. type: String,
  66. default: ''
  67. },
  68. voiceId: {
  69. type: [String, Number],
  70. default: ''
  71. },
  72. bookPages: {
  73. type: Array,
  74. default: () => []
  75. },
  76. isTextPage: {
  77. type: Boolean,
  78. default: false
  79. },
  80. shouldLoadAudio: {
  81. type: Boolean,
  82. default: false
  83. },
  84. isMember: {
  85. type: Boolean,
  86. default: false
  87. },
  88. currentPageRequiresMember: {
  89. type: Boolean,
  90. default: false
  91. },
  92. pagePay: {
  93. type: Array,
  94. default: () => []
  95. },
  96. isWordAudioPlaying: {
  97. type: Boolean,
  98. default: false
  99. }
  100. },
  101. data() {
  102. return {
  103. // 音频控制相关数据
  104. isPlaying: false,
  105. currentTime: 0,
  106. totalTime: 0,
  107. sliderValue: 0, // 滑動條的值
  108. isDragging: false, // 是否正在拖動滑動條
  109. isLoop: false,
  110. playSpeed: 1.0,
  111. speedOptions: [0.5, 0.8, 1.0, 1.25, 1.5, 2.0], // 根據uni-app文檔的官方支持值
  112. playbackRateSupported: true, // 播放速度控制是否支持
  113. // 音频数组管理
  114. currentPageAudios: [], // 当前页面的音频数组
  115. currentAudioIndex: 0, // 当前播放的音频索引
  116. audioContext: null, // 音频上下文
  117. currentAudio: null, // 当前音频实例
  118. // 音频缓存管理
  119. audioCache: {}, // 页面音频缓存 {pageIndex: {audios: [], totalDuration: 0}}
  120. // 预加载相关状态
  121. isPreloading: false, // 是否正在预加载
  122. preloadProgress: 0, // 预加载进度 (0-100)
  123. preloadQueue: [], // 预加载队列
  124. // 音频加载状态
  125. isAudioLoading: false, // 音频是否正在加载
  126. hasAudioData: false, // 当前页面是否已有音频数据
  127. isVoiceChanging: false, // 音色切换中的加载状态
  128. audioLoadFailed: false, // 音频获取失败状态
  129. // 文本高亮相关
  130. currentHighlightIndex: -1, // 当前高亮的文本索引
  131. // 课程切换相关状态
  132. isJustSwitchedCourse: false, // 是否刚刚切换了课程
  133. // 页面切换防抖相关
  134. pageChangeTimer: null, // 页面切换防抖定时器
  135. isPageChanging: false, // 是否正在切换页面
  136. // 请求取消相关
  137. currentRequestId: null, // 当前音频请求ID
  138. shouldCancelRequest: false, // 是否应该取消当前请求
  139. // 本地音色ID(避免直接修改prop)
  140. localVoiceId: '', // 本地音色ID,从prop初始化
  141. // 倍速检查相关
  142. lastSpeedCheckTime: -1, // 上次检查倍速的时间点
  143. // 防抖相关
  144. isProcessingEnded: false, // 防止 onAudioEnded 多次触发
  145. }
  146. },
  147. computed: {
  148. // 计算音频播放进度百分比
  149. progressPercent() {
  150. return this.totalTime > 0 ? (this.currentTime / this.totalTime) * 100 : 0;
  151. },
  152. // 检查当前页面是否有缓存的音频
  153. hasCurrentPageCache() {
  154. const cacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  155. const cachedData = this.audioCache[cacheKey];
  156. // 更严格的缓存有效性检查
  157. if (!cachedData || !cachedData.audios || cachedData.audios.length === 0) {
  158. return false;
  159. }
  160. // 检查缓存的音色ID是否与当前音色匹配
  161. if (cachedData.voiceId && cachedData.voiceId !== this.localVoiceId) {
  162. // console.warn('缓存音色不匹配:', cachedData.voiceId, '!=', this.localVoiceId);
  163. return false;
  164. }
  165. // 检查音频URL是否有效
  166. const firstAudio = cachedData.audios[0];
  167. if (!firstAudio || !firstAudio.url) {
  168. // console.warn('缓存音频数据无效');
  169. return false;
  170. }
  171. return true;
  172. },
  173. // 判断音频功能是否应该被禁用(会员限制页面且用户非会员)
  174. isAudioDisabled() {
  175. // 免费用户不受音频播放限制
  176. if (this.userInfo && this.userInfo.freeUser === 'Y') {
  177. return false;
  178. }
  179. return this.currentPageRequiresMember && !this.isMember;
  180. },
  181. // 检查当前页面是否正在预加载中
  182. isCurrentPagePreloading() {
  183. // 如果全局预加载状态为true,需要检查当前页面是否在预加载队列中
  184. if (this.isPreloading) {
  185. // 检查当前页面是否有缓存(如果有缓存说明已经预加载完成)
  186. const cacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  187. const hasCache = this.audioCache[cacheKey] && this.audioCache[cacheKey].audios && this.audioCache[cacheKey].audios.length > 0;
  188. // 如果没有缓存且正在预加载,说明当前页面可能正在预加载中
  189. if (!hasCache) {
  190. // console.log('当前页面可能正在预加载中,页面:', this.currentPage, '缓存状态:', hasCache);
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. },
  197. watch: {
  198. // 监听页面变化,重置音频状态
  199. currentPage: {
  200. handler(newPage, oldPage) {
  201. if (newPage !== oldPage) {
  202. // console.log('页面切换:', oldPage, '->', newPage);
  203. // 设置页面切换状态
  204. this.isPageChanging = true;
  205. // 立即重置音频状态,防止穿音
  206. this.resetAudioState();
  207. // 清除之前的防抖定时器
  208. if (this.pageChangeTimer) {
  209. clearTimeout(this.pageChangeTimer);
  210. }
  211. // 使用防抖机制,避免频繁切换时重复加载
  212. this.pageChangeTimer = setTimeout(() => {
  213. this.isPageChanging = false;
  214. // 检查新页面是否有预加载完成的音频缓存
  215. this.$nextTick(() => {
  216. this.checkAndLoadPreloadedAudio();
  217. });
  218. }, 300); // 300ms防抖延迟
  219. }
  220. },
  221. immediate: false
  222. },
  223. // 监听音色变化,更新本地音色ID
  224. voiceId: {
  225. handler(newVoiceId, oldVoiceId) {
  226. if (newVoiceId !== oldVoiceId) {
  227. // console.log('🎵 音色ID变化:', oldVoiceId, '->', newVoiceId);
  228. // 更新本地音色ID
  229. this.localVoiceId = newVoiceId;
  230. }
  231. },
  232. immediate: true // 立即执行,用于初始化
  233. },
  234. // 监听页面数据变化,当页面数据重新加载后自动获取音频
  235. bookPages: {
  236. handler(newBookPages, oldBookPages) {
  237. // 检查当前页面数据是否从无到有
  238. const currentPageData = newBookPages && newBookPages[this.currentPage - 1];
  239. const oldCurrentPageData = oldBookPages && oldBookPages[this.currentPage - 1];
  240. if (currentPageData && !oldCurrentPageData && this.shouldLoadAudio && this.courseId) {
  241. console.log(`🎵 bookPages监听: 当前页面数据已加载,自动获取音频,页面=${this.currentPage}`);
  242. this.$nextTick(() => {
  243. this.getCurrentPageAudio(true); // 启用自动播放
  244. });
  245. }
  246. },
  247. deep: true // 深度监听数组变化
  248. }
  249. },
  250. methods: {
  251. // 辅助方法:查找第一个非导语音频的索引
  252. findFirstNonLeadAudio() {
  253. if (!this.currentPageAudios || this.currentPageAudios.length === 0) {
  254. return -1;
  255. }
  256. // 从第一个音频开始查找非导语音频
  257. for (let i = 0; i < this.currentPageAudios.length; i++) {
  258. const audioData = this.currentPageAudios[i];
  259. if (audioData && !audioData.isLead) {
  260. console.log(`🎵 findFirstNonLeadAudio: 找到第一个非导语音频,索引=${i}, isLead=${audioData.isLead}`);
  261. return i;
  262. }
  263. }
  264. // 如果所有音频都是导语,返回 -1 表示不播放
  265. console.log('🎵 findFirstNonLeadAudio: 所有音频都是导语,返回 -1 不播放');
  266. return -1;
  267. },
  268. // 检查并自动加载预加载完成的音频
  269. checkAndLoadPreloadedAudio() {
  270. // 只在需要加载音频的页面检查
  271. if (!this.shouldLoadAudio) {
  272. // 非文本页面,确保音频状态为空
  273. this.currentPageAudios = [];
  274. this.totalTime = 0;
  275. this.hasAudioData = false;
  276. this.isAudioLoading = false;
  277. // 通知父组件音频状态变化
  278. this.$emit('audio-state-change', {
  279. hasAudioData: false,
  280. isLoading: false,
  281. currentHighlightIndex: -1
  282. });
  283. return;
  284. }
  285. // 检查当前页面是否有缓存的音频数据
  286. const pageKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  287. const cachedAudio = this.audioCache[pageKey];
  288. if (cachedAudio && cachedAudio.audios && cachedAudio.audios.length > 0) {
  289. // 有缓存:直接显示控制栏并自动播放
  290. this.currentPageAudios = cachedAudio.audios;
  291. this.totalTime = cachedAudio.totalDuration || 0;
  292. this.hasAudioData = true;
  293. this.isAudioLoading = false;
  294. // 初始化音频索引为第一个非导语音频
  295. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  296. this.currentAudioIndex = firstNonLeadIndex;
  297. this.currentTime = 0;
  298. this.currentHighlightIndex = -1;
  299. console.log(`🎵 checkAndLoadPreloadedAudio: 从缓存加载音频,页面=${this.currentPage}, 音频数量=${this.currentPageAudios.length}`);
  300. // 通知父组件音频状态变化
  301. this.$emit('audio-state-change', {
  302. hasAudioData: true,
  303. isLoading: false,
  304. currentHighlightIndex: -1
  305. });
  306. // 自动播放缓存的音频
  307. this.$nextTick(() => {
  308. if (this.currentPageAudios.length > 0 && !this.isVoiceChanging) {
  309. // 查找第一个非导语音频
  310. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  311. if (firstNonLeadIndex >= 0 && firstNonLeadIndex < this.currentPageAudios.length) {
  312. // 设置当前音频索引为第一个非导语音频
  313. this.currentAudioIndex = firstNonLeadIndex;
  314. const firstAudioData = this.currentPageAudios[firstNonLeadIndex];
  315. console.log(`🎵 自动播放缓存音频(跳过导语): 索引=${firstNonLeadIndex}, isLead=${firstAudioData.isLead}, url=${firstAudioData.url}`);
  316. audioManager.playAudio(firstAudioData.url, 'sentence', { playbackRate: this.playSpeed });
  317. this.isPlaying = true;
  318. // 页面切换时需要立即更新高亮和滚动,不受防抖机制影响
  319. const highlightIndex = firstAudioData.originalTextIndex !== undefined ? firstAudioData.originalTextIndex : firstNonLeadIndex;
  320. this.currentHighlightIndex = highlightIndex;
  321. // 立即发送高亮变化事件
  322. this.emitHighlightChange(highlightIndex, firstAudioData);
  323. // 立即发送滚动事件,传入音频数据
  324. this.emitScrollToText(highlightIndex, firstAudioData);
  325. console.log(`🎵 页面切换自动播放(跳过导语): 高亮索引=${highlightIndex}, 页面=${this.currentPage}`);
  326. }
  327. }
  328. });
  329. } else {
  330. // 没有缓存:自动开始加载音频
  331. console.log(`🎵 checkAndLoadPreloadedAudio: 无缓存,开始加载音频,页面=${this.currentPage}`);
  332. this.getCurrentPageAudio(true); // 启用自动播放
  333. }
  334. },
  335. // 智能分割文本,按句号和逗号分割中英文文本
  336. splitTextIntelligently(text) {
  337. if (!text || typeof text !== 'string') {
  338. return [text];
  339. }
  340. // 判断是否为中文文本(包含中文字符)
  341. const isChinese = /[\u4e00-\u9fa5]/.test(text);
  342. const maxLength = isChinese ? 100 : 200;
  343. // 如果文本长度不超过限制,直接返回
  344. if (text.length <= maxLength) {
  345. return [{
  346. text: text,
  347. startIndex: 0,
  348. endIndex: text.length - 1
  349. }];
  350. }
  351. const segments = [];
  352. let currentText = text;
  353. let globalStartIndex = 0;
  354. while (currentText.length > 0) {
  355. if (currentText.length <= maxLength) {
  356. // 剩余文本不超过限制,直接添加
  357. segments.push({
  358. text: currentText,
  359. startIndex: globalStartIndex,
  360. endIndex: globalStartIndex + currentText.length - 1
  361. });
  362. break;
  363. }
  364. // 在限制长度内寻找最佳分割点
  365. let splitIndex = maxLength;
  366. let bestSplitIndex = -1;
  367. // 优先寻找句号
  368. for (let i = Math.min(maxLength, currentText.length - 1); i >= Math.max(0, maxLength - 50); i--) {
  369. const char = currentText[i];
  370. if (char === '。' || char === '.') {
  371. bestSplitIndex = i + 1; // 包含句号
  372. break;
  373. }
  374. }
  375. // 如果没找到句号,寻找逗号
  376. if (bestSplitIndex === -1) {
  377. for (let i = Math.min(maxLength, currentText.length - 1); i >= Math.max(0, maxLength - 50); i--) {
  378. const char = currentText[i];
  379. if (char === ',' || char === ',' || char === ';' || char === ';') {
  380. bestSplitIndex = i + 1; // 包含标点符号
  381. break;
  382. }
  383. }
  384. }
  385. // 如果还是没找到合适的分割点,使用默认长度
  386. if (bestSplitIndex === -1) {
  387. bestSplitIndex = maxLength;
  388. }
  389. // 提取当前段落
  390. const segment = currentText.substring(0, bestSplitIndex).trim();
  391. if (segment.length > 0) {
  392. segments.push({
  393. text: segment,
  394. startIndex: globalStartIndex,
  395. endIndex: globalStartIndex + segment.length - 1
  396. });
  397. }
  398. // 更新剩余文本和全局索引
  399. currentText = currentText.substring(bestSplitIndex).trim();
  400. globalStartIndex += bestSplitIndex;
  401. }
  402. return segments;
  403. },
  404. // 分批次请求音频
  405. async requestAudioInBatches(text, voiceType) {
  406. const segments = this.splitTextIntelligently(text);
  407. const audioSegments = [];
  408. let totalDuration = 0;
  409. const requestId = this.currentRequestId; // 保存当前请求ID
  410. for (let i = 0; i < segments.length; i++) {
  411. // 检查是否应该取消请求
  412. if (this.shouldCancelRequest || this.currentRequestId !== requestId) {
  413. return null; // 返回null表示请求被取消
  414. }
  415. const segment = segments[i];
  416. try {
  417. console.log(`请求第 ${i + 1}/${segments.length} 段音频:`, segment.text.substring(0, 50) + '...');
  418. const radioRes = await this.$api.music.textToVoice({
  419. text: segment.text,
  420. voiceType: voiceType,
  421. });
  422. if (radioRes.code === 200 && radioRes.result && radioRes.result.url) {
  423. const audioUrl = radioRes.result.url;
  424. const duration = radioRes.result.time || 0;
  425. audioSegments.push({
  426. url: audioUrl,
  427. text: segment.text,
  428. duration: duration,
  429. startIndex: segment.startIndex,
  430. endIndex: segment.endIndex,
  431. segmentIndex: i,
  432. isSegmented: segments.length > 1,
  433. originalText: text
  434. });
  435. totalDuration += duration;
  436. } else {
  437. console.error(`${i + 1} 段音频请求失败:`, radioRes);
  438. // 即使某段失败,也继续处理其他段
  439. audioSegments.push({
  440. url: null,
  441. text: segment.text,
  442. duration: 0,
  443. startIndex: segment.startIndex,
  444. endIndex: segment.endIndex,
  445. segmentIndex: i,
  446. error: true,
  447. isSegmented: segments.length > 1,
  448. originalText: text
  449. });
  450. }
  451. } catch (error) {
  452. console.error(`${i + 1} 段音频请求异常:`, error);
  453. audioSegments.push({
  454. url: null,
  455. text: segment.text,
  456. duration: 0,
  457. startIndex: segment.startIndex,
  458. endIndex: segment.endIndex,
  459. segmentIndex: i,
  460. error: true,
  461. isSegmented: segments.length > 1,
  462. originalText: text
  463. });
  464. }
  465. // 每个请求之间间隔200ms,避免请求过于频繁
  466. if (i < segments.length - 1) {
  467. await new Promise(resolve => setTimeout(resolve, 0));
  468. }
  469. }
  470. console.log(`分批次音频请求完成,成功 ${audioSegments.filter(s => !s.error).length}/${segments.length}`);
  471. return {
  472. audioSegments: audioSegments,
  473. totalDuration: totalDuration,
  474. originalText: text
  475. };
  476. },
  477. // 获取当前页面的音频内容
  478. async getCurrentPageAudio(autoPlay = false) {
  479. // 🎯 确保音色ID已加载完成后再获取音频
  480. if (!this.localVoiceId || this.localVoiceId === '' || this.localVoiceId === null || this.localVoiceId === undefined) {
  481. // 设置加载失败状态
  482. this.isAudioLoading = false;
  483. this.audioLoadFailed = true;
  484. this.hasAudioData = false;
  485. // 通知父组件音频状态变化
  486. this.$emit('audio-state-change', {
  487. hasAudioData: false,
  488. isLoading: false,
  489. currentHighlightIndex: -1
  490. });
  491. uni.showToast({
  492. title: '音色未加载,请稍后重试',
  493. icon: 'none',
  494. duration: 2000
  495. });
  496. return;
  497. }
  498. // 检查是否正在页面切换中,如果是则不加载音频
  499. if (this.isPageChanging) {
  500. return;
  501. }
  502. // 检查是否需要加载音频
  503. if (!this.shouldLoadAudio) {
  504. // 清空音频状态
  505. this.currentPageAudios = [];
  506. this.hasAudioData = false;
  507. this.isAudioLoading = false;
  508. this.audioLoadFailed = false;
  509. this.currentAudioIndex = 0;
  510. this.currentTime = 0;
  511. this.totalTime = 0;
  512. this.currentHighlightIndex = -1;
  513. // 通知父组件音频状态变化
  514. this.$emit('audio-state-change', {
  515. hasAudioData: false,
  516. isLoading: false,
  517. currentHighlightIndex: -1
  518. });
  519. return;
  520. }
  521. // 检查会员限制
  522. if (this.isAudioDisabled) {
  523. return;
  524. }
  525. // 检查是否已经在加载中,防止重复加载(音色切换时除外)
  526. if (this.isAudioLoading && !this.isVoiceChanging) {
  527. return;
  528. }
  529. console.log('this.audioCache:', this.audioCache);
  530. // 检查缓存中是否已有当前页面的音频数据
  531. const cacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  532. if (this.audioCache[cacheKey]) {
  533. // 从缓存加载音频数据
  534. this.currentPageAudios = this.audioCache[cacheKey].audios;
  535. this.totalTime = this.audioCache[cacheKey].totalDuration;
  536. // 初始化音频索引为第一个非导语音频
  537. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  538. this.currentAudioIndex = firstNonLeadIndex;
  539. this.isPlaying = false;
  540. this.currentTime = 0;
  541. this.hasAudioData = true;
  542. this.isAudioLoading = false;
  543. // 如果是课程切换后的自动加载,清除切换标识
  544. if (this.isJustSwitchedCourse) {
  545. this.isJustSwitchedCourse = false;
  546. }
  547. // 通知父组件音频状态变化
  548. this.$emit('audio-state-change', {
  549. hasAudioData: this.hasAudioData,
  550. isLoading: this.isAudioLoading,
  551. currentHighlightIndex: this.currentHighlightIndex
  552. });
  553. return;
  554. }
  555. // 开始加载状态
  556. this.isAudioLoading = true;
  557. this.hasAudioData = false;
  558. // 重置请求取消标识并生成新的请求ID
  559. this.shouldCancelRequest = false;
  560. this.currentRequestId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  561. // 清空当前页面音频数组
  562. this.currentPageAudios = [];
  563. this.currentAudioIndex = 0;
  564. this.isPlaying = false;
  565. this.currentTime = 0;
  566. this.totalTime = 0;
  567. // 通知父组件开始加载
  568. this.$emit('audio-state-change', {
  569. hasAudioData: this.hasAudioData,
  570. isLoading: this.isAudioLoading,
  571. currentHighlightIndex: this.currentHighlightIndex
  572. });
  573. try {
  574. // 对着当前页面的每一个[]元素进行切割 如果是文本text类型则进行音频请求
  575. const currentPageData = this.bookPages[this.currentPage - 1];
  576. console.log(`🎵 getCurrentPageAudio: 当前页面=${this.currentPage}, 音色ID=${this.localVoiceId}, 课程ID=${this.courseId}`);
  577. console.log(`🎵 getCurrentPageAudio: bookPages长度=${this.bookPages.length}, 当前页面数据:`, currentPageData);
  578. // 检查页面数据是否存在且不为空
  579. if (!currentPageData || currentPageData.length === 0) {
  580. console.log(`🎵 getCurrentPageAudio: 当前页面数据为空,可能还在加载中`);
  581. // 通知父组件页面数据需要加载
  582. this.$emit('page-data-needed', this.currentPage);
  583. // 设置加载失败状态
  584. this.isAudioLoading = false;
  585. this.audioLoadFailed = true;
  586. this.hasAudioData = false;
  587. // 通知父组件音频状态变化
  588. this.$emit('audio-state-change', {
  589. hasAudioData: false,
  590. isLoading: false,
  591. currentHighlightIndex: -1
  592. });
  593. uni.showToast({
  594. title: '页面数据加载中,请稍后重试',
  595. icon: 'none',
  596. duration: 2000
  597. });
  598. return;
  599. }
  600. if (currentPageData) {
  601. // 收集所有text类型的元素
  602. const textItems = currentPageData.filter(item => item.type === 'text');
  603. console.log(`🎵 getCurrentPageAudio: 找到${textItems.length}个文本项:`, textItems.map(item => item.content?.substring(0, 50) + '...'));
  604. if (textItems.length > 0) {
  605. let firstAudioPlayed = false; // 标记是否已播放第一个音频
  606. let loadedAudiosCount = 0; // 已加载的音频数量
  607. // 逐个处理文本项,支持长文本分割
  608. for (let index = 0; index < textItems.length; index++) {
  609. const item = textItems[index];
  610. try {
  611. // 使用分批次请求音频
  612. const batchResult = await this.requestAudioInBatches(item.content, this.localVoiceId);
  613. // 检查请求是否被取消
  614. if (batchResult === null) {
  615. return;
  616. }
  617. if (batchResult.audioSegments.length > 0) {
  618. // 同时保存到原始数据中以保持兼容性(使用第一段的URL)
  619. const firstValidSegment = batchResult.audioSegments.find(seg => !seg.error);
  620. if (firstValidSegment) {
  621. item.audioUrl = firstValidSegment.url;
  622. }
  623. // 将所有音频段添加到音频数组
  624. for (const segment of batchResult.audioSegments) {
  625. if (!segment.error) {
  626. const audioData = {
  627. isLead : item.isLead,
  628. url: segment.url,
  629. text: segment.text,
  630. duration: segment.duration,
  631. startIndex: segment.startIndex,
  632. endIndex: segment.endIndex,
  633. segmentIndex: segment.segmentIndex,
  634. originalTextIndex: index, // 标记属于哪个原始文本项
  635. isSegmented: batchResult.audioSegments.length > 1 // 标记是否为分段音频
  636. };
  637. this.currentPageAudios.push(audioData);
  638. loadedAudiosCount++;
  639. }
  640. }
  641. // 如果是第一个音频,立即开始播放
  642. if (!firstAudioPlayed && this.currentPageAudios.length > 0) {
  643. firstAudioPlayed = true;
  644. this.hasAudioData = true;
  645. // 初始化音频索引为第一个非导语音频
  646. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  647. this.currentAudioIndex = firstNonLeadIndex >= 0 ? firstNonLeadIndex : 0;
  648. // 通知父组件有音频数据了,但仍在加载中
  649. this.$emit('audio-state-change', {
  650. hasAudioData: this.hasAudioData,
  651. isLoading: this.isAudioLoading, // 保持加载状态
  652. currentHighlightIndex: this.currentHighlightIndex
  653. });
  654. // 立即使用audioManager播放第一个非导语音频
  655. if (autoPlay || !this.isVoiceChanging) {
  656. // 查找第一个非导语音频
  657. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  658. if (firstNonLeadIndex >= 0 && firstNonLeadIndex < this.currentPageAudios.length) {
  659. // 设置当前音频索引为第一个非导语音频
  660. this.currentAudioIndex = firstNonLeadIndex;
  661. const firstAudioData = this.currentPageAudios[firstNonLeadIndex];
  662. console.log(`🎵 getCurrentPageAudio 自动播放(跳过导语): 索引=${firstNonLeadIndex}, isLead=${firstAudioData.isLead}`);
  663. audioManager.playAudio(firstAudioData.url, 'sentence', { playbackRate: this.playSpeed });
  664. this.isPlaying = true;
  665. this.updateHighlightIndex();
  666. }
  667. }
  668. }
  669. console.log(`文本项 ${index + 1} 处理完成,获得 ${batchResult.audioSegments.filter(s => !s.error).length} 个音频段`);
  670. } else {
  671. console.error(`文本项 ${index + 1} 音频请求全部失败`);
  672. }
  673. } catch (error) {
  674. console.error(`文本项 ${index + 1} 处理异常:`, error);
  675. }
  676. }
  677. // 如果有音频,重新计算精确的总时长
  678. if (this.currentPageAudios.length > 0) {
  679. await this.calculateTotalDuration();
  680. // 将音频数据保存到缓存中
  681. const cacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  682. this.audioCache[cacheKey] = {
  683. audios: [...this.currentPageAudios], // 深拷贝音频数组
  684. totalDuration: this.totalTime,
  685. voiceId: this.localVoiceId, // 保存音色ID用于验证
  686. timestamp: Date.now() // 保存时间戳
  687. };
  688. // 限制缓存大小
  689. this.limitCacheSize(1000);
  690. }
  691. }
  692. }
  693. // 结束加载状态
  694. this.isAudioLoading = false;
  695. this.isVoiceChanging = false; // 清除音色切换加载状态
  696. // 如果是课程切换后的自动加载,清除切换标识
  697. if (this.isJustSwitchedCourse) {
  698. this.isJustSwitchedCourse = false;
  699. }
  700. // 设置音频数据状态和失败状态
  701. this.hasAudioData = this.currentPageAudios.length > 0;
  702. this.audioLoadFailed = !this.hasAudioData && this.shouldLoadAudio; // 如果需要音频但没有音频数据,则认为获取失败
  703. // 通知父组件音频状态变化
  704. this.$emit('audio-state-change', {
  705. hasAudioData: this.hasAudioData,
  706. isLoading: this.isAudioLoading,
  707. audioLoadFailed: this.audioLoadFailed,
  708. currentHighlightIndex: this.currentHighlightIndex
  709. });
  710. } catch (error) {
  711. console.error('getCurrentPageAudio 方法执行异常:', error);
  712. // 确保在异常情况下重置加载状态
  713. this.isAudioLoading = false;
  714. this.isVoiceChanging = false;
  715. this.audioLoadFailed = true;
  716. this.hasAudioData = false;
  717. // 通知父组件音频加载失败
  718. this.$emit('audio-state-change', {
  719. hasAudioData: false,
  720. isLoading: false,
  721. audioLoadFailed: true,
  722. currentHighlightIndex: this.currentHighlightIndex
  723. });
  724. // 显示错误提示
  725. uni.showToast({
  726. title: '音频加载失败,请重试',
  727. icon: 'none',
  728. duration: 2000
  729. });
  730. }
  731. },
  732. // 重新获取音频
  733. retryGetAudio() {
  734. // 检查是否需要加载音频
  735. if (!this.shouldLoadAudio) {
  736. return;
  737. }
  738. // 重置失败状态
  739. this.audioLoadFailed = false;
  740. // 清除当前页面的音频缓存
  741. const pageKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  742. if (this.audioCache[pageKey]) {
  743. delete this.audioCache[pageKey];
  744. }
  745. // 重新获取音频
  746. this.getCurrentPageAudio();
  747. },
  748. // 重置音频状态
  749. resetAudioState() {
  750. // 取消当前正在进行的音频请求
  751. this.shouldCancelRequest = true;
  752. // 使用audioManager停止当前音频
  753. audioManager.stopCurrentAudio();
  754. this.currentAudio = null;
  755. // 重置播放状态
  756. this.currentAudioIndex = 0;
  757. this.isPlaying = false;
  758. this.currentTime = 0;
  759. this.totalTime = 0;
  760. this.sliderValue = 0;
  761. this.isAudioLoading = false;
  762. this.audioLoadFailed = false;
  763. this.currentHighlightIndex = -1;
  764. this.playSpeed = 1.0;
  765. // 页面切换时,始终清空当前音频数据,避免数据错乱
  766. // 音频数据的加载由checkAndLoadPreloadedAudio方法统一处理
  767. this.currentPageAudios = [];
  768. this.totalTime = 0;
  769. this.hasAudioData = false;
  770. // 通知父组件音频状态变化
  771. this.$emit('audio-state-change', {
  772. hasAudioData: false,
  773. isLoading: false,
  774. currentHighlightIndex: -1
  775. });
  776. },
  777. // 加载缓存的音频数据并显示播放控制栏
  778. loadCachedAudioData() {
  779. const cacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  780. const cachedData = this.audioCache[cacheKey];
  781. // 严格验证缓存数据
  782. if (!cachedData || !cachedData.audios || cachedData.audios.length === 0) {
  783. console.warn('缓存数据不存在或为空:', cacheKey);
  784. uni.showToast({
  785. title: '缓存音频数据不存在',
  786. icon: 'none'
  787. });
  788. return;
  789. }
  790. // 检查音色ID是否匹配
  791. if (cachedData.voiceId && cachedData.voiceId !== this.localVoiceId) {
  792. console.warn('缓存音色不匹配:', cachedData.voiceId, '!=', this.localVoiceId);
  793. // uni.showToast({
  794. // title: '音色已切换,请重新获取音频',
  795. // icon: 'none'
  796. // });
  797. return;
  798. }
  799. // 检查音频URL是否有效
  800. const firstAudio = cachedData.audios[0];
  801. if (!firstAudio || !firstAudio.url) {
  802. console.warn('缓存音频URL无效');
  803. uni.showToast({
  804. title: '缓存音频数据损坏',
  805. icon: 'none'
  806. });
  807. return;
  808. }
  809. // 从缓存加载音频数据
  810. this.currentPageAudios = cachedData.audios;
  811. this.totalTime = cachedData.totalDuration || 0;
  812. this.currentAudioIndex = 0;
  813. this.isPlaying = false;
  814. this.currentTime = 0;
  815. this.hasAudioData = true;
  816. this.isAudioLoading = false;
  817. this.audioLoadFailed = false;
  818. this.currentHighlightIndex = -1;
  819. // 通知父组件音频状态变化
  820. this.$emit('audio-state-change', {
  821. hasAudioData: this.hasAudioData,
  822. isLoading: this.isAudioLoading,
  823. currentHighlightIndex: this.currentHighlightIndex
  824. });
  825. },
  826. // 手动获取音频
  827. async handleGetAudio() {
  828. // 检查会员限制
  829. if (this.isAudioDisabled) {
  830. return;
  831. }
  832. // 检查是否有音色ID
  833. if (!this.localVoiceId) {
  834. // uni.showToast({
  835. // title: '音色未加载,请稍后重试',
  836. // icon: 'none'
  837. // });
  838. return;
  839. }
  840. // 检查当前页面是否支持音频播放
  841. if (!this.shouldLoadAudio) {
  842. uni.showToast({
  843. title: '当前页面不支持音频播放',
  844. icon: 'none'
  845. });
  846. return;
  847. }
  848. // 检查是否正在加载
  849. if (this.isAudioLoading) {
  850. return;
  851. }
  852. // 调用获取音频方法
  853. await this.getCurrentPageAudio();
  854. },
  855. // 计算音频总时长
  856. async calculateTotalDuration() {
  857. let totalDuration = 0;
  858. for (let i = 0; i < this.currentPageAudios.length; i++) {
  859. const audio = this.currentPageAudios[i];
  860. // 使用API返回的准确时长信息
  861. if (audio.duration && audio.duration > 0) {
  862. totalDuration += audio.duration;
  863. } else {
  864. // 如果没有时长信息,使用文字长度估算(备用方案)
  865. const textLength = audio.text.length;
  866. // 假设较快语速每分钟约300个字符,即每秒约5个字符
  867. const estimatedDuration = Math.max(1, textLength / 5);
  868. audio.duration = estimatedDuration;
  869. totalDuration += estimatedDuration;
  870. console.log(`备用估算音频时长 ${i + 1}:`, estimatedDuration, '秒 (文字长度:', textLength, ')');
  871. }
  872. }
  873. this.totalTime = 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. if (!resolved && audio.duration && audio.duration > 0) {
  884. resolved = true;
  885. resolve(audio.duration);
  886. audio.destroy();
  887. }
  888. });
  889. // 监听音频元数据加载完成事件
  890. audio.onLoadedmetadata = () => {
  891. if (!resolved && audio.duration && audio.duration > 0) {
  892. resolved = true;
  893. resolve(audio.duration);
  894. audio.destroy();
  895. }
  896. };
  897. // 监听音频时长更新事件
  898. audio.onDurationChange = () => {
  899. if (!resolved && audio.duration && audio.duration > 0) {
  900. resolved = true;
  901. resolve(audio.duration);
  902. audio.destroy();
  903. }
  904. };
  905. // 移除onPlay監聽器,避免意外播放
  906. audio.onError((error) => {
  907. console.error('音频加载失败:', error);
  908. if (!resolved) {
  909. resolved = true;
  910. reject(error);
  911. audio.destroy();
  912. }
  913. });
  914. // 設置較長的超時時間,但不播放音頻
  915. setTimeout(() => {
  916. if (!resolved) {
  917. resolved = true;
  918. reject(new Error('無法獲取音頻時長'));
  919. audio.destroy();
  920. }
  921. }, 1000);
  922. // 最終超時處理
  923. setTimeout(() => {
  924. if (!resolved) {
  925. console.warn('獲取音頻時長超時,使用默認值');
  926. resolved = true;
  927. reject(new Error('获取音频时长超时'));
  928. audio.destroy();
  929. }
  930. }, 5000);
  931. });
  932. },
  933. // 音频控制方法
  934. togglePlay() {
  935. // 检查会员限制
  936. if (this.isAudioDisabled) {
  937. return;
  938. }
  939. if (this.currentPageAudios.length === 0) {
  940. uni.showToast({
  941. title: '当前页面没有音频内容',
  942. icon: 'none'
  943. });
  944. return;
  945. }
  946. if (this.isPlaying) {
  947. this.pauseAudio();
  948. } else {
  949. this.playAudio();
  950. }
  951. },
  952. // 播放音频
  953. async playAudio() {
  954. // 检查会员限制
  955. if (this.isAudioDisabled) {
  956. return;
  957. }
  958. // 检查音频数据有效性
  959. if (!this.currentPageAudios || this.currentPageAudios.length === 0) {
  960. console.warn('🎵 playAudio: 没有音频数据');
  961. return;
  962. }
  963. // 如果当前索引无效,重置为第一个非导语音频
  964. if (this.currentAudioIndex < 0 || this.currentAudioIndex >= this.currentPageAudios.length) {
  965. console.log('🎵 playAudio: 音频索引无效,重置为第一个非导语音频');
  966. this.currentAudioIndex = this.findFirstNonLeadAudio();
  967. if (this.currentAudioIndex < 0) {
  968. console.error('🎵 playAudio: 找不到有效的音频');
  969. return;
  970. }
  971. }
  972. let currentAudioData = this.currentPageAudios[this.currentAudioIndex];
  973. // 如果当前音频是导语,跳转到下一个非导语音频
  974. if (currentAudioData && currentAudioData.isLead) {
  975. console.log(`🎵 playAudio: 当前音频是导语(索引=${this.currentAudioIndex}),查找下一个非导语音频`);
  976. // 从当前索引开始查找下一个非导语音频
  977. let nextNonLeadIndex = -1;
  978. for (let i = this.currentAudioIndex; i < this.currentPageAudios.length; i++) {
  979. const audioData = this.currentPageAudios[i];
  980. if (audioData && !audioData.isLead) {
  981. nextNonLeadIndex = i;
  982. break;
  983. }
  984. }
  985. if (nextNonLeadIndex >= 0) {
  986. this.currentAudioIndex = nextNonLeadIndex;
  987. currentAudioData = this.currentPageAudios[this.currentAudioIndex];
  988. console.log(`🎵 playAudio: 跳转到非导语音频,新索引=${this.currentAudioIndex}, isLead=${currentAudioData.isLead}`);
  989. } else {
  990. console.warn('🎵 playAudio: 没有找到非导语音频,播放当前音频');
  991. }
  992. }
  993. if (!currentAudioData || !currentAudioData.url) {
  994. console.error('🎵 playAudio: 音频数据无效', currentAudioData);
  995. return;
  996. }
  997. // 检查音频数据是否属于当前页面
  998. const audioCacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  999. const currentPageCache = this.audioCache[audioCacheKey];
  1000. if (!currentPageCache || !currentPageCache.audios.includes(currentAudioData)) {
  1001. console.error('🎵 playAudio: 音频数据与当前页面不匹配,停止播放');
  1002. return;
  1003. }
  1004. try {
  1005. console.log(`🎵 playAudio: 播放音频,索引=${this.currentAudioIndex}, isLead=${currentAudioData.isLead}`);
  1006. // 使用audioManager播放句子音频,应用全局语速设置
  1007. await audioManager.playAudio(currentAudioData.url, 'sentence', {
  1008. playbackRate: audioManager.getGlobalPlaybackRate()
  1009. });
  1010. // 更新高亮索引
  1011. this.updateHighlightIndex();
  1012. } catch (error) {
  1013. console.error('🎵 播放音频失败:', error);
  1014. uni.showToast({
  1015. title: '音频播放失败',
  1016. icon: 'none'
  1017. });
  1018. }
  1019. },
  1020. // 暂停音频
  1021. pauseAudio() {
  1022. audioManager.pause();
  1023. this.isPlaying = false;
  1024. // 暂停时清除高亮
  1025. this.currentHighlightIndex = -1;
  1026. // 通知父组件高亮状态变化
  1027. this.emitHighlightChange(-1);
  1028. },
  1029. // 文本标准化函数 - 移除多余空格、标点符号等
  1030. normalizeText(text) {
  1031. if (!text || typeof text !== 'string') return '';
  1032. return text
  1033. .trim()
  1034. .replace(/\s+/g, ' ') // 将多个空格替换为单个空格
  1035. .replace(/[,。!?;:""''()【】《》]/g, '') // 移除中文标点
  1036. .replace(/[,.!?;:"'()\[\]<>]/g, '') // 移除英文标点
  1037. .toLowerCase(); // 转为小写(对英文有效)
  1038. },
  1039. // 备用方案:使用 TTS API 实时生成并播放音频
  1040. // async playTextWithTTS(textContent) {
  1041. // try {
  1042. // // 停止当前播放的音频
  1043. // if (this.currentAudio) {
  1044. // this.currentAudio.pause();
  1045. // this.currentAudio.destroy();
  1046. // this.currentAudio = null;
  1047. // }
  1048. // // 显示加载提示
  1049. // uni.showLoading({
  1050. // title: '正在生成音频...'
  1051. // });
  1052. // // 调用 TTS API
  1053. // const audioRes = await this.$api.music.textToVoice({
  1054. // text: textContent,
  1055. // voiceType: this.voiceId || 1 // 使用当前语音类型,默认为1
  1056. // });
  1057. // uni.hideLoading();
  1058. // if (audioRes && audioRes.result && audioRes.result.url) {
  1059. // const audioUrl = audioRes.result.url;
  1060. // // 创建并播放音频
  1061. // const audio = uni.createInnerAudioContext();
  1062. // audio.src = audioUrl;
  1063. // audio.onPlay(() => {
  1064. // this.isPlaying = true;
  1065. // });
  1066. // audio.onEnded(() => {
  1067. // this.isPlaying = false;
  1068. // audio.destroy();
  1069. // if (this.currentAudio === audio) {
  1070. // this.currentAudio = null;
  1071. // }
  1072. // });
  1073. // audio.onError((error) => {
  1074. // console.error('🔊 TTS 音频播放失败:', error);
  1075. // this.isPlaying = false;
  1076. // audio.destroy();
  1077. // if (this.currentAudio === audio) {
  1078. // this.currentAudio = null;
  1079. // }
  1080. // uni.showToast({
  1081. // title: '音频播放失败',
  1082. // icon: 'none'
  1083. // });
  1084. // });
  1085. // // 保存当前音频实例并播放
  1086. // this.currentAudio = audio;
  1087. // audio.play();
  1088. // return true;
  1089. // } else {
  1090. // console.error('❌ TTS API 请求失败:', audioRes);
  1091. // uni.showToast({
  1092. // title: '音频生成失败',
  1093. // icon: 'none'
  1094. // });
  1095. // return false;
  1096. // }
  1097. // } catch (error) {
  1098. // uni.hideLoading();
  1099. // console.error('❌ TTS 音频生成异常:', error);
  1100. // uni.showToast({
  1101. // title: '音频生成失败',
  1102. // icon: 'none'
  1103. // });
  1104. // return false;
  1105. // }
  1106. // },
  1107. // 播放指定的音频段落(通过文本内容匹配)
  1108. playSpecificAudio(textContent) {
  1109. // 检查textContent是否有效
  1110. if (!textContent || typeof textContent !== 'string') {
  1111. console.error('❌ 无效的文本内容:', textContent);
  1112. uni.showToast({
  1113. title: '无效的文本内容',
  1114. icon: 'none'
  1115. });
  1116. return false;
  1117. }
  1118. // 检查音频数据是否已加载
  1119. if (this.currentPageAudios.length === 0) {
  1120. console.warn('⚠️ 当前页面音频数据为空,可能还在加载中');
  1121. uni.showToast({
  1122. title: '音频正在加载中,请稍后再试',
  1123. icon: 'none'
  1124. });
  1125. return false;
  1126. }
  1127. // 标准化目标文本
  1128. const normalizedTarget = this.normalizeText(textContent);
  1129. // 打印所有音频文本用于调试
  1130. this.currentPageAudios.forEach((audio, index) => {
  1131. console.log(` [${index}] 标准化文本: "${this.normalizeText(audio.text)}"`);
  1132. if (audio.originalText) {
  1133. }
  1134. });
  1135. let audioIndex = -1;
  1136. // 第一步:精确匹配(标准化后)
  1137. audioIndex = this.currentPageAudios.findIndex(audio => {
  1138. if (!audio.text) return false;
  1139. const normalizedAudio = this.normalizeText(audio.text);
  1140. return normalizedAudio === normalizedTarget;
  1141. });
  1142. if (audioIndex !== -1) {
  1143. } else {
  1144. // 第二步:包含匹配
  1145. audioIndex = this.currentPageAudios.findIndex(audio => {
  1146. if (!audio.text) return false;
  1147. const normalizedAudio = this.normalizeText(audio.text);
  1148. // 双向包含检查
  1149. return normalizedAudio.includes(normalizedTarget) || normalizedTarget.includes(normalizedAudio);
  1150. });
  1151. if (audioIndex !== -1) {
  1152. } else {
  1153. // 第三步:分段音频匹配
  1154. audioIndex = this.currentPageAudios.findIndex(audio => {
  1155. if (!audio.text) return false;
  1156. // 检查是否为分段音频,且原始文本匹配
  1157. if (audio.isSegmented && audio.originalText) {
  1158. const normalizedOriginal = this.normalizeText(audio.originalText);
  1159. return normalizedOriginal === normalizedTarget ||
  1160. normalizedOriginal.includes(normalizedTarget) ||
  1161. normalizedTarget.includes(normalizedOriginal);
  1162. }
  1163. return false;
  1164. });
  1165. if (audioIndex !== -1) {
  1166. } else {
  1167. // 第四步:句子分割匹配(针对长句子)
  1168. // 将目标句子按标点符号分割
  1169. const targetSentences = normalizedTarget.split(/[,。!?;:,!?;:]/).filter(s => s.trim().length > 0);
  1170. if (targetSentences.length > 1) {
  1171. // 尝试匹配分割后的句子片段
  1172. for (let i = 0; i < targetSentences.length; i++) {
  1173. const sentence = targetSentences[i].trim();
  1174. if (sentence.length < 3) continue; // 跳过太短的片段
  1175. audioIndex = this.currentPageAudios.findIndex(audio => {
  1176. if (!audio.text) return false;
  1177. const normalizedAudio = this.normalizeText(audio.text);
  1178. return normalizedAudio.includes(sentence) || sentence.includes(normalizedAudio);
  1179. });
  1180. if (audioIndex !== -1) {
  1181. break;
  1182. }
  1183. }
  1184. }
  1185. if (audioIndex === -1) {
  1186. // 第五步:关键词匹配(提取关键词进行匹配)
  1187. const keywords = normalizedTarget.split(/\s+/).filter(word => word.length > 2);
  1188. let bestKeywordMatch = -1;
  1189. let bestKeywordCount = 0;
  1190. this.currentPageAudios.forEach((audio, index) => {
  1191. if (!audio.text) return;
  1192. const normalizedAudio = this.normalizeText(audio.text);
  1193. // 计算匹配的关键词数量
  1194. const matchedKeywords = keywords.filter(keyword => normalizedAudio.includes(keyword));
  1195. const matchCount = matchedKeywords.length;
  1196. if (matchCount > bestKeywordCount && matchCount >= Math.min(2, keywords.length)) {
  1197. bestKeywordCount = matchCount;
  1198. bestKeywordMatch = index;
  1199. console.log(` [${index}] 关键词匹配: ${matchCount}/${keywords.length}, 匹配词: [${matchedKeywords.join(', ')}]`);
  1200. }
  1201. });
  1202. if (bestKeywordMatch !== -1) {
  1203. audioIndex = bestKeywordMatch;
  1204. } else {
  1205. // 第六步:相似度匹配(最后的尝试)
  1206. let bestMatch = -1;
  1207. let bestSimilarity = 0;
  1208. this.currentPageAudios.forEach((audio, index) => {
  1209. if (!audio.text) return;
  1210. const normalizedAudio = this.normalizeText(audio.text);
  1211. // 计算简单的相似度(共同字符数 / 较长文本长度)
  1212. const commonChars = [...normalizedTarget].filter(char => normalizedAudio.includes(char)).length;
  1213. const maxLength = Math.max(normalizedTarget.length, normalizedAudio.length);
  1214. const similarity = maxLength > 0 ? commonChars / maxLength : 0;
  1215. console.log(` [${index}] 相似度: ${similarity.toFixed(2)}, 文本: "${audio.text}"`);
  1216. if (similarity > bestSimilarity && similarity > 0.5) { // 降低相似度阈值到50%
  1217. bestSimilarity = similarity;
  1218. bestMatch = index;
  1219. }
  1220. });
  1221. if (bestMatch !== -1) {
  1222. audioIndex = bestMatch;
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. if (audioIndex !== -1) {
  1230. // 使用audioManager停止当前音频并播放新音频
  1231. audioManager.stopCurrentAudio();
  1232. // 设置新的音频索引
  1233. this.currentAudioIndex = audioIndex;
  1234. // 重置播放状态
  1235. this.isPlaying = false;
  1236. this.currentTime = 0;
  1237. this.sliderValue = 0;
  1238. // 更新高亮索引
  1239. this.currentHighlightIndex = audioIndex;
  1240. this.emitHighlightChange(audioIndex);
  1241. // 使用audioManager播放指定音频
  1242. const audioData = this.currentPageAudios[audioIndex];
  1243. audioManager.playAudio(audioData.url, 'sentence', { playbackRate: this.playSpeed });
  1244. this.isPlaying = true;
  1245. return true; // 成功找到并播放
  1246. } else {
  1247. console.error('❌ 未找到匹配的音频段落:', textContent);
  1248. // 最后的尝试:首字符匹配(针对划线重点等特殊情况)
  1249. if (normalizedTarget.length > 5) {
  1250. const firstChars = normalizedTarget.substring(0, Math.min(10, normalizedTarget.length));
  1251. audioIndex = this.currentPageAudios.findIndex(audio => {
  1252. if (!audio.text) return false;
  1253. const normalizedAudio = this.normalizeText(audio.text);
  1254. return normalizedAudio.startsWith(firstChars) || firstChars.startsWith(normalizedAudio.substring(0, Math.min(10, normalizedAudio.length)));
  1255. });
  1256. if (audioIndex !== -1) {
  1257. // 使用audioManager停止当前音频并播放新音频
  1258. audioManager.stopCurrentAudio();
  1259. // 设置新的音频索引
  1260. this.currentAudioIndex = audioIndex;
  1261. // 重置播放状态
  1262. this.isPlaying = false;
  1263. this.currentTime = 0;
  1264. this.sliderValue = 0;
  1265. // 更新高亮索引
  1266. this.currentHighlightIndex = audioIndex;
  1267. this.emitHighlightChange(audioIndex);
  1268. // 使用audioManager播放指定音频
  1269. const audioData = this.currentPageAudios[audioIndex];
  1270. audioManager.playAudio(audioData.url, 'sentence', { playbackRate: this.playSpeed });
  1271. this.isPlaying = true;
  1272. return true;
  1273. }
  1274. }
  1275. // 备用方案:当找不到匹配音频时,显示提示信息
  1276. console.warn('⚠️ 未找到匹配的音频段落,无法播放:', textContent);
  1277. this.$emit('showToast', '未找到对应的音频内容');
  1278. return false;
  1279. }
  1280. },
  1281. // 创建音频实例
  1282. // 更新当前播放时间
  1283. updateCurrentTime() {
  1284. // 使用audioManager获取当前播放时间
  1285. const currentTime = audioManager.getCurrentTime();
  1286. if (currentTime === null) return;
  1287. let totalTime = 0;
  1288. // 计算之前音频的总时长
  1289. for (let i = 0; i < this.currentAudioIndex; i++) {
  1290. totalTime += this.currentPageAudios[i].duration;
  1291. }
  1292. // 加上当前音频的播放时间
  1293. totalTime += currentTime;
  1294. this.currentTime = totalTime;
  1295. // 如果不是正在拖動滑動條,則同步更新滑動條的值
  1296. if (!this.isDragging) {
  1297. this.sliderValue = this.currentTime;
  1298. }
  1299. // 更新当前高亮的文本索引
  1300. this.updateHighlightIndex();
  1301. },
  1302. // 更新高亮文本索引
  1303. updateHighlightIndex() {
  1304. if (!this.isPlaying || this.currentPageAudios.length === 0) {
  1305. this.currentHighlightIndex = -1;
  1306. this.emitHighlightChange(-1);
  1307. return;
  1308. }
  1309. // 检查是否正在页面切换中,如果是则不更新高亮
  1310. if (this.isPageChanging) {
  1311. return;
  1312. }
  1313. // 获取当前播放的音频数据
  1314. const currentAudio = this.currentPageAudios[this.currentAudioIndex];
  1315. if (!currentAudio) {
  1316. this.currentHighlightIndex = -1;
  1317. this.emitHighlightChange(-1);
  1318. return;
  1319. }
  1320. // 检查音频数据是否属于当前页面,防止页面切换时的数据错乱
  1321. const audioCacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  1322. const currentPageCache = this.audioCache[audioCacheKey];
  1323. // 如果当前音频数据不属于当前页面,则不更新高亮
  1324. if (!currentPageCache || !currentPageCache.audios.includes(currentAudio)) {
  1325. console.warn('🎵 updateHighlightIndex: 音频数据与当前页面不匹配,跳过高亮更新');
  1326. return;
  1327. }
  1328. // 如果是分段音频,需要计算正确的高亮索引
  1329. if (currentAudio.isSegmented && typeof currentAudio.originalTextIndex !== 'undefined') {
  1330. // 使用原始文本项的索引作为高亮索引
  1331. this.currentHighlightIndex = currentAudio.originalTextIndex;
  1332. } else {
  1333. // 非分段音频,使用音频索引
  1334. this.currentHighlightIndex = this.currentAudioIndex;
  1335. }
  1336. // 使用辅助方法发送高亮变化事件
  1337. this.emitHighlightChange(this.currentHighlightIndex);
  1338. // 发送滚动事件,让页面滚动到当前高亮的文本
  1339. this.emitScrollToText(this.currentHighlightIndex);
  1340. },
  1341. // 发送高亮变化事件的辅助方法
  1342. emitHighlightChange(highlightIndex = -1, audioData = null) {
  1343. if (highlightIndex === -1) {
  1344. // 清除高亮
  1345. this.$emit('highlight-change', -1);
  1346. return;
  1347. }
  1348. // 获取当前播放的音频数据,优先使用传入的audioData
  1349. const currentAudioData = audioData || this.currentPageAudios[this.currentAudioIndex];
  1350. if (!currentAudioData) {
  1351. this.$emit('highlight-change', -1);
  1352. return;
  1353. }
  1354. const highlightData = {
  1355. highlightIndex: currentAudioData.originalTextIndex !== undefined ? currentAudioData.originalTextIndex : highlightIndex,
  1356. isSegmented: currentAudioData.isSegmented || false,
  1357. segmentIndex: currentAudioData.segmentIndex || 0,
  1358. startIndex: currentAudioData.startIndex || 0,
  1359. endIndex: currentAudioData.endIndex || 0,
  1360. currentText: currentAudioData.text || ''
  1361. };
  1362. // 发送详细的高亮信息
  1363. this.$emit('highlight-change', highlightData);
  1364. },
  1365. // 发送滚动到文本事件的辅助方法
  1366. emitScrollToText(highlightIndex = -1, audioData = null) {
  1367. if (highlightIndex === -1) {
  1368. return;
  1369. }
  1370. // 获取当前播放的音频数据,优先使用传入的audioData
  1371. const currentAudioData = audioData || this.currentPageAudios[this.currentAudioIndex];
  1372. if (!currentAudioData) {
  1373. return;
  1374. }
  1375. // 检查音频数据是否属于当前页面,防止页面切换时的数据错乱
  1376. const audioCacheKey = `${this.courseId}_${this.currentPage}_${this.localVoiceId}`;
  1377. const currentPageCache = this.audioCache[audioCacheKey];
  1378. // 如果当前音频数据不属于当前页面,则不发送滚动事件
  1379. if (!currentPageCache || !currentPageCache.audios.includes(currentAudioData)) {
  1380. console.warn('🎵 emitScrollToText: 音频数据与当前页面不匹配,跳过滚动事件');
  1381. return;
  1382. }
  1383. const scrollData = {
  1384. highlightIndex: currentAudioData.originalTextIndex !== undefined ? currentAudioData.originalTextIndex : highlightIndex,
  1385. isSegmented: currentAudioData.isSegmented || false,
  1386. segmentIndex: currentAudioData.segmentIndex || 0,
  1387. currentText: currentAudioData.text || '',
  1388. currentPage: this.currentPage
  1389. };
  1390. // 发送滚动事件
  1391. this.$emit('scroll-to-text', scrollData);
  1392. },
  1393. // 音频播放结束处理
  1394. onAudioEnded() {
  1395. // 防止多次触发,添加防抖机制
  1396. if (this.isProcessingEnded) {
  1397. console.log('🎵 onAudioEnded: 正在处理中,跳过重复调用');
  1398. return;
  1399. }
  1400. this.isProcessingEnded = true;
  1401. console.log(`🎵 onAudioEnded: 当前索引=${this.currentAudioIndex}, 总音频数=${this.currentPageAudios.length}`);
  1402. // 添加延迟确保音频状态完全清理
  1403. setTimeout(() => {
  1404. try {
  1405. // 检查音频数据有效性
  1406. if (!this.currentPageAudios || this.currentPageAudios.length === 0) {
  1407. console.warn('🎵 onAudioEnded: 没有音频数据');
  1408. this.isProcessingEnded = false;
  1409. return;
  1410. }
  1411. if (this.currentAudioIndex < this.currentPageAudios.length - 1) {
  1412. // 还有下一个音频,继续播放
  1413. let currentAudioData = this.currentPageAudios[this.currentAudioIndex];
  1414. // 检查当前音频的 isLead 状态
  1415. if (currentAudioData && !currentAudioData.isLead) {
  1416. console.log('🎵 onAudioEnded: 当前音频 isLead=false,检查是否需要跳过 isLead=true 的音频');
  1417. // 从当前索引开始,跳过所有 isLead=true 的音频
  1418. let nextIndex = this.currentAudioIndex;
  1419. while (nextIndex < (this.currentPageAudios.length - 1)) {
  1420. const audioData = this.currentPageAudios[nextIndex + 1];
  1421. if (audioData && audioData.isLead == true) {
  1422. console.log(`🎵 onAudioEnded: 跳过 isLead=true 的音频,索引=${nextIndex + 1}`);
  1423. nextIndex++;
  1424. } else {
  1425. break;
  1426. }
  1427. }
  1428. // 更新当前音频索引
  1429. if (nextIndex !== this.currentAudioIndex) {
  1430. this.currentAudioIndex = nextIndex;
  1431. console.log(`🎵 onAudioEnded: 跳过后的新索引=${this.currentAudioIndex}`);
  1432. // 检查新索引是否有效
  1433. if (this.currentAudioIndex >= this.currentPageAudios.length - 1) {
  1434. console.log('🎵 onAudioEnded: 跳过后已到达音频列表末尾,进入播放完毕逻辑');
  1435. // 跳转到播放完毕的逻辑
  1436. this.handlePlaybackComplete();
  1437. return;
  1438. }
  1439. }
  1440. }
  1441. // 移动到下一个音频索引
  1442. this.currentAudioIndex++;
  1443. // 确保索引在有效范围内
  1444. if (this.currentAudioIndex >= this.currentPageAudios.length) {
  1445. console.log('🎵 onAudioEnded: 索引超出范围,进入播放完毕逻辑');
  1446. this.handlePlaybackComplete();
  1447. return;
  1448. }
  1449. console.log(`🎵 onAudioEnded: 准备播放下一个音频,索引=${this.currentAudioIndex}`);
  1450. // 确保音频数据有效
  1451. const nextAudio = this.currentPageAudios[this.currentAudioIndex];
  1452. if (nextAudio && nextAudio.url) {
  1453. this.playAudio();
  1454. } else {
  1455. console.error('🎵 onAudioEnded: 下一个音频数据无效', nextAudio);
  1456. // 如果下一个音频无效,尝试播放再下一个
  1457. this.findAndPlayNextValidAudio();
  1458. }
  1459. } else {
  1460. // 所有音频播放完毕
  1461. this.handlePlaybackComplete();
  1462. }
  1463. } catch (error) {
  1464. console.error('🎵 onAudioEnded: 处理过程中发生错误', error);
  1465. } finally {
  1466. // 重置防抖标志
  1467. this.isProcessingEnded = false;
  1468. }
  1469. }, 50); // 添加50ms延迟确保状态清理完成
  1470. },
  1471. // 处理播放完毕的逻辑
  1472. handlePlaybackComplete() {
  1473. console.log('🎵 handlePlaybackComplete: 所有音频播放完毕');
  1474. if (this.isLoop) {
  1475. // 循环播放 - 跳过导语音频
  1476. console.log('🎵 handlePlaybackComplete: 循环播放,查找第一个非导语音频');
  1477. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  1478. if (firstNonLeadIndex >= 0 && firstNonLeadIndex < this.currentPageAudios.length) {
  1479. this.currentAudioIndex = firstNonLeadIndex;
  1480. const firstAudio = this.currentPageAudios[firstNonLeadIndex];
  1481. if (firstAudio && firstAudio.url) {
  1482. console.log(`🎵 handlePlaybackComplete: 循环播放从非导语音频开始,索引=${firstNonLeadIndex}, isLead=${firstAudio.isLead}`);
  1483. this.playAudio();
  1484. } else {
  1485. console.error('🎵 handlePlaybackComplete: 第一个非导语音频数据无效,停止循环播放');
  1486. this.stopPlayback();
  1487. }
  1488. } else {
  1489. console.error('🎵 handlePlaybackComplete: 找不到有效的非导语音频,停止循环播放');
  1490. this.stopPlayback();
  1491. }
  1492. } else {
  1493. // 停止播放
  1494. this.stopPlayback();
  1495. }
  1496. },
  1497. // 停止播放的逻辑
  1498. stopPlayback() {
  1499. console.log('🎵 stopPlayback: 播放完毕,停止播放');
  1500. this.isPlaying = false;
  1501. this.currentTime = this.totalTime;
  1502. this.currentHighlightIndex = -1;
  1503. this.$emit('highlight-change', -1);
  1504. // 通知父组件音频状态变化
  1505. this.$emit('audio-state-change', {
  1506. hasAudioData: this.hasAudioData,
  1507. isLoading: false,
  1508. currentHighlightIndex: -1
  1509. });
  1510. },
  1511. // 查找并播放下一个有效的音频
  1512. findAndPlayNextValidAudio() {
  1513. console.log('🎵 findAndPlayNextValidAudio: 查找下一个有效音频');
  1514. // 从当前索引开始查找有效音频
  1515. for (let i = this.currentAudioIndex + 1; i < this.currentPageAudios.length; i++) {
  1516. const audio = this.currentPageAudios[i];
  1517. if (audio && audio.url) {
  1518. console.log(`🎵 findAndPlayNextValidAudio: 找到有效音频,索引=${i}`);
  1519. this.currentAudioIndex = i;
  1520. this.playAudio();
  1521. return;
  1522. }
  1523. }
  1524. // 没有找到有效音频,播放完毕
  1525. console.log('🎵 findAndPlayNextValidAudio: 没有找到有效音频,播放完毕');
  1526. this.handlePlaybackComplete();
  1527. },
  1528. // 滚动到当前播放音频对应的文字
  1529. // scrollToCurrentAudio() {
  1530. // try {
  1531. // // 获取当前播放的音频数据
  1532. // const currentAudio = this.currentPageAudios[this.currentAudioIndex];
  1533. // if (!currentAudio) {
  1534. // console.log('🔍 scrollToCurrentAudio: 没有当前音频数据');
  1535. // return;
  1536. // }
  1537. //
  1538. // // 确定要滚动到的文字索引
  1539. // let targetTextIndex = this.currentAudioIndex;
  1540. //
  1541. // // 如果是分段音频,使用原始文本索引
  1542. // if (currentAudio.isSegmented && typeof currentAudio.originalTextIndex !== 'undefined') {
  1543. // targetTextIndex = currentAudio.originalTextIndex;
  1544. // }
  1545. //
  1546. // // 获取当前页面数据
  1547. // const currentPageData = this.bookPages[this.currentPage - 1];
  1548. // if (!currentPageData || !Array.isArray(currentPageData)) {
  1549. // console.warn('⚠️ scrollToCurrentAudio: 无法获取当前页面数据');
  1550. // return;
  1551. // }
  1552. //
  1553. // // 判断目标索引位置的元素类型
  1554. // const targetElement = currentPageData[targetTextIndex];
  1555. // let refPrefix = 'textRef'; // 默认为文本
  1556. //
  1557. // if (targetElement && targetElement.type === 'image') {
  1558. // refPrefix = 'imageRef';
  1559. // }
  1560. //
  1561. // // 构建ref名称:根据元素类型使用不同前缀
  1562. // const refName = `${refPrefix}_${this.currentPage - 1}_${targetTextIndex}`;
  1563. //
  1564. // console.log('🎯 scrollToCurrentAudio:', {
  1565. // currentAudioIndex: this.currentAudioIndex,
  1566. // targetTextIndex: targetTextIndex,
  1567. // targetElementType: targetElement?.type || 'unknown',
  1568. // refPrefix: refPrefix,
  1569. // refName: refName,
  1570. // isSegmented: currentAudio.isSegmented,
  1571. // originalTextIndex: currentAudio.originalTextIndex,
  1572. // audioText: currentAudio.text?.substring(0, 50) + '...'
  1573. // });
  1574. //
  1575. // // 通过父组件调用scrollTo插件
  1576. // this.$emit('scroll-to-text', refName);
  1577. //
  1578. // } catch (error) {
  1579. // console.error('❌ scrollToCurrentAudio 执行失败:', error);
  1580. // }
  1581. // },
  1582. toggleLoop() {
  1583. this.isLoop = !this.isLoop;
  1584. },
  1585. toggleSpeed() {
  1586. // 简化检测:只在极少数情况下阻止倍速切换
  1587. // 只有在明确禁用的情况下才阻止(比如Android 4.x)
  1588. if (!this.playbackRateSupported) {
  1589. // 不再直接返回,而是继续尝试
  1590. }
  1591. const currentIndex = this.speedOptions.indexOf(this.playSpeed);
  1592. const nextIndex = (currentIndex + 1) % this.speedOptions.length;
  1593. const oldSpeed = this.playSpeed;
  1594. this.playSpeed = this.speedOptions[nextIndex];
  1595. // 同步语速设置到audioManager
  1596. audioManager.setGlobalPlaybackRate(this.playSpeed);
  1597. console.log('⚡ 倍速切换详情:', {
  1598. 可用选项: this.speedOptions,
  1599. 当前索引: currentIndex,
  1600. 下一个索引: nextIndex,
  1601. 旧速度: oldSpeed + 'x',
  1602. 新速度: this.playSpeed + 'x',
  1603. 切换时间: new Date().toLocaleTimeString()
  1604. });
  1605. // 同步全局播放速度到audioManager
  1606. audioManager.setGlobalPlaybackRate(this.playSpeed);
  1607. // 显示速度变更提示
  1608. uni.showToast({
  1609. title: `🎵 播放速度: ${this.playSpeed}x`,
  1610. icon: 'none',
  1611. duration: 1000
  1612. });
  1613. },
  1614. // 滑動條值實時更新 (@input 事件)
  1615. onSliderInput(value) {
  1616. // 在拖動過程中實時更新顯示的時間,但不影響實際播放
  1617. if (this.isDragging) {
  1618. // 可以在這裡實時更新顯示時間,讓用戶看到拖動到的時間點
  1619. // 但不改變實際的 currentTime,避免影響播放邏輯
  1620. }
  1621. },
  1622. // 滑動條拖動過程中的處理 (@changing 事件)
  1623. onSliderChanging(value) {
  1624. // 第一次觸發 changing 事件時,暫停播放並標記為拖動狀態
  1625. if (!this.isDragging) {
  1626. if (this.isPlaying) {
  1627. this.pauseAudio();
  1628. }
  1629. this.isDragging = true;
  1630. }
  1631. // 更新滑動條的值,但不改變實際播放位置
  1632. this.sliderValue = value;
  1633. },
  1634. // 滑動條拖動結束的處理 (@change 事件)
  1635. onSliderChange(value) {
  1636. // 如果不是拖動狀態(即單點),需要先暫停播放
  1637. if (!this.isDragging && this.isPlaying) {
  1638. this.pauseAudio();
  1639. }
  1640. // 重置拖動狀態
  1641. this.isDragging = false;
  1642. this.sliderValue = value;
  1643. // 跳轉到指定位置,但不自動恢復播放
  1644. this.seekToTime(value, false);
  1645. },
  1646. // 跳轉到指定時間
  1647. seekToTime(targetTime, shouldResume = false) {
  1648. if (!this.currentPageAudios || this.currentPageAudios.length === 0) {
  1649. return;
  1650. }
  1651. // 確保目標時間在有效範圍內
  1652. targetTime = Math.max(0, Math.min(targetTime, this.totalTime));
  1653. let accumulatedTime = 0;
  1654. let targetAudioIndex = -1;
  1655. let targetAudioTime = 0;
  1656. // 找到目標時間對應的音頻片段
  1657. for (let i = 0; i < this.currentPageAudios.length; i++) {
  1658. const audioDuration = this.currentPageAudios[i].duration || 0;
  1659. if (targetTime >= accumulatedTime && targetTime <= accumulatedTime + audioDuration) {
  1660. targetAudioIndex = i;
  1661. targetAudioTime = targetTime - accumulatedTime;
  1662. break;
  1663. }
  1664. accumulatedTime += audioDuration;
  1665. }
  1666. // 如果沒有找到合適的音頻片段,使用最後一個
  1667. if (targetAudioIndex === -1 && this.currentPageAudios.length > 0) {
  1668. targetAudioIndex = this.currentPageAudios.length - 1;
  1669. targetAudioTime = this.currentPageAudios[targetAudioIndex].duration || 0;
  1670. }
  1671. if (targetAudioIndex === -1) {
  1672. console.error('無法找到目標音頻片段');
  1673. return;
  1674. }
  1675. // 如果需要切換到不同的音頻片段
  1676. if (targetAudioIndex !== this.currentAudioIndex) {
  1677. this.currentAudioIndex = targetAudioIndex;
  1678. // 使用audioManager播放指定音频并跳转到指定时间
  1679. const audioData = this.currentPageAudios[targetAudioIndex];
  1680. audioManager.playAudio(audioData.url, 'sentence', { playbackRate: this.playSpeed, startTime: targetAudioTime });
  1681. this.currentTime = targetTime;
  1682. if (shouldResume) {
  1683. this.isPlaying = true;
  1684. } else {
  1685. // 如果不需要恢复播放,则暂停
  1686. audioManager.pause();
  1687. this.isPlaying = false;
  1688. }
  1689. } else {
  1690. // 在當前音頻片段內跳轉
  1691. audioManager.seekTo(targetAudioTime);
  1692. this.currentTime = targetTime;
  1693. if (shouldResume) {
  1694. audioManager.resume();
  1695. this.isPlaying = true;
  1696. }
  1697. }
  1698. },
  1699. // 等待音頻實例準備就緒
  1700. waitForAudioReady(callback, maxAttempts = 10, currentAttempt = 0) {
  1701. if (currentAttempt >= maxAttempts) {
  1702. console.error('音頻實例準備超時');
  1703. return;
  1704. }
  1705. if (this.currentAudio && this.currentAudio.src) {
  1706. // 音頻實例已準備好
  1707. setTimeout(callback, 50); // 稍微延遲確保完全準備好
  1708. } else {
  1709. // 繼續等待
  1710. setTimeout(() => {
  1711. this.waitForAudioReady(callback, maxAttempts, currentAttempt + 1);
  1712. }, 100);
  1713. }
  1714. },
  1715. // 初始检测播放速度支持(简化版本,默认启用)
  1716. checkInitialPlaybackRateSupport() {
  1717. try {
  1718. const systemInfo = uni.getSystemInfoSync();
  1719. console.log('📱 系统信息:', {
  1720. platform: systemInfo.platform,
  1721. system: systemInfo.system,
  1722. SDKVersion: systemInfo.SDKVersion,
  1723. brand: systemInfo.brand,
  1724. model: systemInfo.model
  1725. });
  1726. // 简化检测逻辑:默认启用倍速功能
  1727. // 只在极少数明确不支持的情况下禁用
  1728. this.playbackRateSupported = true;
  1729. // 仅对非常老的Android版本进行限制(Android 4.x及以下)
  1730. if (systemInfo.platform === 'android') {
  1731. const androidVersion = systemInfo.system.match(/Android (\d+)/);
  1732. if (androidVersion && parseInt(androidVersion[1]) < 5) {
  1733. this.playbackRateSupported = false;
  1734. console.log(`⚠️ Android版本过低 (${androidVersion[1]}),禁用倍速功能`);
  1735. uni.showToast({
  1736. title: `Android ${androidVersion[1]} 不支持倍速`,
  1737. icon: 'none',
  1738. duration: 2000
  1739. });
  1740. return;
  1741. }
  1742. }
  1743. // 显示成功提示
  1744. // uni.showToast({
  1745. // title: '✅ 倍速功能可用',
  1746. // icon: 'none',
  1747. // duration: 1500
  1748. // });
  1749. } catch (error) {
  1750. console.error('💥 检测播放速度支持时出错:', error);
  1751. // 即使出错也默认启用
  1752. this.playbackRateSupported = true;
  1753. }
  1754. },
  1755. // 应用播放速度设置
  1756. applyPlaybackRate(audio) {
  1757. if (!audio) return;
  1758. console.log('📊 当前状态检查:', {
  1759. playbackRateSupported: this.playbackRateSupported,
  1760. 期望速度: this.playSpeed + 'x',
  1761. 音频当前速度: audio.playbackRate + 'x',
  1762. 音频播放状态: this.isPlaying ? '播放中' : '未播放'
  1763. });
  1764. if (this.playbackRateSupported) {
  1765. try {
  1766. // 多次尝试设置倍速,确保生效
  1767. const maxAttempts = 3;
  1768. let attempt = 0;
  1769. const trySetRate = () => {
  1770. attempt++;
  1771. audio.playbackRate = this.playSpeed;
  1772. setTimeout(() => {
  1773. const actualRate = audio.playbackRate;
  1774. const rateDifference = Math.abs(actualRate - this.playSpeed);
  1775. if (rateDifference >= 0.01 && attempt < maxAttempts) {
  1776. setTimeout(trySetRate, 100);
  1777. } else if (rateDifference < 0.01) {
  1778. } else {
  1779. }
  1780. }, 50);
  1781. };
  1782. trySetRate();
  1783. } catch (error) {
  1784. }
  1785. } else {
  1786. }
  1787. },
  1788. // 检查播放速度控制支持(简化版本)
  1789. checkPlaybackRateSupport(audio) {
  1790. try {
  1791. // 如果初始检测已经禁用,直接返回
  1792. if (!this.playbackRateSupported) {
  1793. return;
  1794. }
  1795. console.log('🎧 音频实例信息:', {
  1796. 音频对象存在: !!audio,
  1797. 音频对象类型: typeof audio,
  1798. 音频src: audio ? audio.src : '无'
  1799. });
  1800. // 检测音频实例类型和倍速支持
  1801. let isHTML5Audio = false;
  1802. let supportsPlaybackRate = false;
  1803. if (audio) {
  1804. // 检查是否为HTML5 Audio包装实例
  1805. if (audio._nativeAudio && audio._nativeAudio instanceof Audio) {
  1806. isHTML5Audio = true;
  1807. supportsPlaybackRate = true;
  1808. }
  1809. // 检查是否为原生HTML5 Audio
  1810. else if (audio instanceof Audio) {
  1811. isHTML5Audio = true;
  1812. supportsPlaybackRate = true;
  1813. }
  1814. // 检查uni-app音频实例的playbackRate属性
  1815. else if (typeof audio.playbackRate !== 'undefined') {
  1816. supportsPlaybackRate = true;
  1817. } else {
  1818. }
  1819. // console.log('🔍 音频实例分析:', {
  1820. // 是否HTML5Audio: isHTML5Audio,
  1821. // 支持倍速: supportsPlaybackRate,
  1822. // 实例类型: audio.constructor?.name || 'unknown',
  1823. // playbackRate属性: typeof audio.playbackRate
  1824. // });
  1825. // 如果支持倍速,尝试设置当前播放速度
  1826. if (supportsPlaybackRate) {
  1827. try {
  1828. const currentSpeed = this.playSpeed || 1.0;
  1829. audio.playbackRate = currentSpeed;
  1830. // console.log(`🔧 设置播放速度为 ${currentSpeed}x`);
  1831. // 验证设置结果
  1832. // setTimeout(() => {
  1833. // const actualRate = audio.playbackRate;
  1834. // console.log('🔍 播放速度验证:', {
  1835. // 期望值: currentSpeed,
  1836. // 实际值: actualRate,
  1837. // 设置成功: Math.abs(actualRate - currentSpeed) < 0.1
  1838. // });
  1839. // }, 50);
  1840. } catch (error) {
  1841. }
  1842. }
  1843. } else {
  1844. }
  1845. // 保持倍速功能启用状态
  1846. } catch (error) {
  1847. console.error('💥 检查播放速度支持时出错:', error);
  1848. // 即使出错也保持启用状态
  1849. }
  1850. },
  1851. formatTime(seconds) {
  1852. const mins = Math.floor(seconds / 60);
  1853. const secs = Math.floor(seconds % 60);
  1854. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  1855. },
  1856. // 清理音频缓存
  1857. clearAudioCache() {
  1858. this.audioCache = {};
  1859. },
  1860. // 限制缓存大小,保留最近访问的页面
  1861. limitCacheSize(maxSize = 10) {
  1862. const cacheKeys = Object.keys(this.audioCache);
  1863. if (cacheKeys.length > maxSize) {
  1864. // 删除最旧的缓存项
  1865. const keysToDelete = cacheKeys.slice(0, cacheKeys.length - maxSize);
  1866. keysToDelete.forEach(key => {
  1867. delete this.audioCache[key];
  1868. });
  1869. }
  1870. },
  1871. // 自動加載第一頁音頻並播放
  1872. async autoLoadAndPlayFirstPage() {
  1873. try {
  1874. // 確保當前是第一頁且需要加載音頻
  1875. if (this.currentPage === 1 && this.shouldLoadAudio) {
  1876. // 加載音頻
  1877. await this.getCurrentPageAudio();
  1878. // 檢查是否成功加載音頻
  1879. if (this.currentPageAudios && this.currentPageAudios.length > 0) {
  1880. // getCurrentPageAudio方法已經處理了第一個音頻的播放,這裡不需要再次調用playAudio
  1881. } else {
  1882. }
  1883. } else {
  1884. }
  1885. } catch (error) {
  1886. console.error('自動加載和播放音頻失敗:', error);
  1887. }
  1888. },
  1889. // 清理音频资源
  1890. destroyAudio() {
  1891. // 使用audioManager停止当前音频
  1892. audioManager.stopCurrentAudio();
  1893. // 重置所有播放状态
  1894. this.isPlaying = false;
  1895. this.currentTime = 0;
  1896. this.sliderValue = 0;
  1897. this.currentHighlightIndex = -1;
  1898. // 清理音频缓存
  1899. this.clearAudioCache();
  1900. // 取消正在进行的请求
  1901. this.shouldCancelRequest = true;
  1902. // 重置加载状态
  1903. this.isAudioLoading = false;
  1904. this.isVoiceChanging = false;
  1905. this.audioLoadFailed = false;
  1906. },
  1907. // 停止单词音频播放(全局音频管理)
  1908. stopWordAudio() {
  1909. // 使用audioManager停止当前音频(如果是单词音频)
  1910. if (audioManager.currentAudioType === 'word') {
  1911. audioManager.stopCurrentAudio();
  1912. }
  1913. },
  1914. // 课程切换时的完整数据清理(保留音色设置)
  1915. resetForCourseChange() {
  1916. // 停止当前音频播放
  1917. if (this.isPlaying) {
  1918. this.pauseAudio();
  1919. }
  1920. // 使用audioManager停止当前音频
  1921. audioManager.stopCurrentAudio();
  1922. // 清空所有音频相关数据
  1923. this.currentPageAudios = [];
  1924. this.currentAudioIndex = 0;
  1925. this.currentTime = 0;
  1926. this.totalTime = 0;
  1927. this.sliderValue = 0;
  1928. this.isDragging = false;
  1929. this.isPlaying = false;
  1930. this.hasAudioData = false;
  1931. this.isAudioLoading = false;
  1932. this.audioLoadFailed = false;
  1933. this.currentHighlightIndex = -1;
  1934. // 3. 清空音频缓存(因为课程变了,所有缓存都无效)
  1935. this.clearAudioCache();
  1936. // 4. 重置预加载状态
  1937. this.isPreloading = false;
  1938. this.preloadProgress = 0;
  1939. this.preloadedPages = new Set();
  1940. // 5. 重置播放控制状态
  1941. this.isLoop = false;
  1942. this.playSpeed = 1.0;
  1943. this.playbackRateSupported = true;
  1944. // 6. 重置音色切换状态
  1945. this.isVoiceChanging = false;
  1946. // 7. 设置课程切换状态
  1947. this.isJustSwitchedCourse = true;
  1948. // 注意:不清空 voiceId,保留用户的音色选择
  1949. // 7. 通知父组件状态变化
  1950. this.$emit('audio-state-change', {
  1951. hasAudioData: false,
  1952. isLoading: false,
  1953. audioLoadFailed: false,
  1954. currentHighlightIndex: -1
  1955. });
  1956. },
  1957. // 自动加载并播放音频(课程切换后调用)
  1958. async autoLoadAndPlayAudio() {
  1959. // 检查是否需要加载音频
  1960. if (!this.shouldLoadAudio) {
  1961. return;
  1962. }
  1963. // 检查必要条件
  1964. if (!this.courseId || !this.currentPage) {
  1965. return;
  1966. }
  1967. try {
  1968. // 设置加载状态
  1969. this.isAudioLoading = true;
  1970. // 开始加载音频
  1971. await this.getCurrentPageAudio();
  1972. } catch (error) {
  1973. console.error('自动加载音频失败:', error);
  1974. this.isAudioLoading = false;
  1975. }
  1976. },
  1977. // 暂停音频(页面隐藏时调用)
  1978. pauseOnHide() {
  1979. this.pauseAudio();
  1980. },
  1981. // 处理音色切换(由父组件调用)
  1982. async handleVoiceChange(newVoiceId, options = {}) {
  1983. console.log(`🎵 handleVoiceChange: 开始音色切换 ${this.localVoiceId} -> ${newVoiceId}`);
  1984. console.log(`🎵 handleVoiceChange: 当前页面=${this.currentPage}, 课程ID=${this.courseId}, bookPages长度=${this.bookPages.length}`);
  1985. // 检查是否正在加载音频,如果是则阻止音色切换
  1986. if (this.isAudioLoading) {
  1987. console.log(`🎵 handleVoiceChange: 音频正在加载中,阻止音色切换`);
  1988. throw new Error('音频加载中,请稍后再试');
  1989. }
  1990. const { preloadAllPages = true } = options; // 默认预加载所有页面
  1991. try {
  1992. // 1. 停止当前播放的音频
  1993. if (this.isPlaying) {
  1994. this.pauseAudio();
  1995. }
  1996. // 2. 销毁当前音频实例
  1997. audioManager.stopCurrentAudio();
  1998. this.currentAudio = null;
  1999. // 3. 清理所有音频缓存(因为音色变了,所有缓存都无效)
  2000. this.clearAudioCache();
  2001. // 4. 重置音频状态
  2002. this.currentPageAudios = [];
  2003. this.currentAudioIndex = 0;
  2004. this.isPlaying = false;
  2005. this.currentTime = 0;
  2006. this.totalTime = 0;
  2007. this.hasAudioData = false;
  2008. this.audioLoadFailed = false;
  2009. this.currentHighlightIndex = -1;
  2010. // 5. 设置音色切换加载状态
  2011. this.isVoiceChanging = true;
  2012. this.isAudioLoading = true;
  2013. // 6. 更新本地音色ID(不直接修改prop)
  2014. this.localVoiceId = newVoiceId;
  2015. // 7. 通知父组件开始加载状态
  2016. this.$emit('audio-state-change', {
  2017. hasAudioData: false,
  2018. isLoading: true,
  2019. currentHighlightIndex: -1
  2020. });
  2021. // 8. 如果当前页面需要加载音频,优先获取当前页面音频
  2022. if (this.shouldLoadAudio && this.courseId && this.currentPage) {
  2023. console.log(`🎵 handleVoiceChange: 开始获取当前页面音频,页面=${this.currentPage}, 课程=${this.courseId}`);
  2024. await this.getCurrentPageAudio();
  2025. console.log(`🎵 handleVoiceChange: 当前页面音频获取完成,hasAudioData=${this.hasAudioData}`);
  2026. } else {
  2027. // 如果不需要加载音频,直接清除加载状态
  2028. console.log(`🎵 handleVoiceChange: 不需要加载音频,shouldLoadAudio=${this.shouldLoadAudio}, courseId=${this.courseId}, currentPage=${this.currentPage}`);
  2029. this.isAudioLoading = false;
  2030. }
  2031. // 9. 清除音色切换加载状态
  2032. this.isVoiceChanging = false;
  2033. // 10. 如果需要预加载其他页面,启动预加载
  2034. if (preloadAllPages) {
  2035. // 延迟启动预加载,确保当前页面音频加载完成
  2036. setTimeout(() => {
  2037. this.preloadAllPagesAudio();
  2038. }, 1000);
  2039. }
  2040. // 11. 通知父组件最终状态
  2041. this.$emit('audio-state-change', {
  2042. hasAudioData: this.hasAudioData,
  2043. isLoading: this.isAudioLoading,
  2044. currentHighlightIndex: this.currentHighlightIndex
  2045. });
  2046. // 12. 通知父组件音色切换完成
  2047. this.$emit('voice-change-complete', {
  2048. voiceId: newVoiceId,
  2049. hasAudioData: this.hasAudioData,
  2050. preloadAllPages: preloadAllPages
  2051. });
  2052. } catch (error) {
  2053. console.error('🎵 AudioControls: 音色切换处理失败:', error);
  2054. // 清除加载状态
  2055. this.isVoiceChanging = false;
  2056. this.isAudioLoading = false;
  2057. // 通知父组件状态变化
  2058. this.$emit('audio-state-change', {
  2059. hasAudioData: false,
  2060. isLoading: false,
  2061. currentHighlightIndex: -1
  2062. });
  2063. this.$emit('voice-change-error', error);
  2064. }
  2065. },
  2066. // 预加载所有页面音频(音色切换时使用)
  2067. async preloadAllPagesAudio() {
  2068. if (this.isPreloading) {
  2069. return;
  2070. }
  2071. try {
  2072. this.isPreloading = true;
  2073. this.preloadProgress = 0;
  2074. // 获取所有文本页面
  2075. const allTextPages = [];
  2076. for (let i = 0; i < this.bookPages.length; i++) {
  2077. const pageData = this.bookPages[i];
  2078. const hasTextContent = pageData && pageData.some(item => item.type === 'text');
  2079. if (hasTextContent && i !== this.currentPage - 1) { // 排除当前页面,因为已经加载过了
  2080. allTextPages.push({
  2081. pageIndex: i + 1,
  2082. pageData: pageData
  2083. });
  2084. }
  2085. }
  2086. if (allTextPages.length === 0) {
  2087. this.isPreloading = false;
  2088. return;
  2089. }
  2090. // 逐页预加载音频
  2091. for (let i = 0; i < allTextPages.length; i++) {
  2092. const pageInfo = allTextPages[i];
  2093. try {
  2094. console.log(`预加载第 ${pageInfo.pageIndex} 页音频 (${i + 1}/${allTextPages.length})`);
  2095. await this.preloadPageAudio(pageInfo.pageIndex, pageInfo.pageData);
  2096. // 更新进度
  2097. this.preloadProgress = Math.round(((i + 1) / allTextPages.length) * 100);
  2098. // 添加小延迟,避免请求过于频繁
  2099. if (i < allTextPages.length - 1) {
  2100. await new Promise(resolve => setTimeout(resolve, 100));
  2101. }
  2102. } catch (error) {
  2103. console.error(`预加载第 ${pageInfo.pageIndex} 页音频失败:`, error);
  2104. // 继续预加载其他页面,不因单页失败而中断
  2105. }
  2106. }
  2107. } catch (error) {
  2108. console.error('预加载所有页面音频失败:', error);
  2109. } finally {
  2110. this.isPreloading = false;
  2111. this.preloadProgress = 100;
  2112. }
  2113. },
  2114. // 开始预加载音频(由父组件调用)
  2115. async startPreloadAudio() {
  2116. if (this.isPreloading) {
  2117. return;
  2118. }
  2119. try {
  2120. this.isPreloading = true;
  2121. this.preloadProgress = 0;
  2122. // 获取需要预加载的页面列表(当前页面后的几页)
  2123. const preloadPages = this.getPreloadPageList();
  2124. if (preloadPages.length === 0) {
  2125. this.isPreloading = false;
  2126. return;
  2127. }
  2128. // 逐个预加载页面音频
  2129. for (let i = 0; i < preloadPages.length; i++) {
  2130. const pageInfo = preloadPages[i];
  2131. try {
  2132. await this.preloadPageAudio(pageInfo.pageIndex, pageInfo.pageData);
  2133. // 更新预加载进度
  2134. this.preloadProgress = Math.round(((i + 1) / preloadPages.length) * 100);
  2135. // 延迟一下,避免请求过于频繁
  2136. await new Promise(resolve => setTimeout(resolve, 150));
  2137. } catch (error) {
  2138. console.error(`预加载第${pageInfo.pageIndex + 1}页音频失败:`, error);
  2139. // 继续预加载其他页面
  2140. }
  2141. }
  2142. } catch (error) {
  2143. console.error('预加载音频失败:', error);
  2144. } finally {
  2145. this.isPreloading = false;
  2146. this.preloadProgress = 100;
  2147. }
  2148. },
  2149. // 获取需要预加载的页面列表
  2150. getPreloadPageList() {
  2151. const preloadPages = [];
  2152. const maxPreloadPages = 3; // 优化:最多预加载3页,减少服务器压力
  2153. // 从当前页面的下一页开始预加载
  2154. for (let i = this.currentPage; i < Math.min(this.currentPage + maxPreloadPages, this.bookPages.length); i++) {
  2155. const pageData = this.bookPages[i];
  2156. // 检查页面是否需要会员且用户非会员,如果是则跳过
  2157. const pageRequiresMember = this.pagePay[i] === 'Y';
  2158. // 免费用户不受会员限制
  2159. const isFreeUser = this.userInfo && this.userInfo.freeUser === 'Y';
  2160. if (pageRequiresMember && !this.isMember && !isFreeUser) {
  2161. continue;
  2162. }
  2163. // 检查页面是否有文本内容且未缓存
  2164. if (pageData && pageData.length > 0) {
  2165. const hasTextContent = pageData.some(item => item.type === 'text' && item.content);
  2166. const cacheKey = `${this.courseId}_${i + 1}_${this.voiceId}`;
  2167. const isAlreadyCached = this.audioCache[cacheKey];
  2168. if (hasTextContent && !isAlreadyCached) {
  2169. preloadPages.push({
  2170. pageIndex: i,
  2171. pageData: pageData
  2172. });
  2173. }
  2174. }
  2175. }
  2176. return preloadPages;
  2177. },
  2178. // 预加载单个页面的音频
  2179. async preloadPageAudio(pageIndex, pageData) {
  2180. const cacheKey = `${this.courseId}_${pageIndex + 1}_${this.voiceId}`;
  2181. // 检查是否已经缓存
  2182. if (this.audioCache[cacheKey]) {
  2183. return;
  2184. }
  2185. // 收集页面中的文本内容
  2186. const textItems = pageData.filter(item => item.type === 'text' && item.content);
  2187. if (textItems.length === 0) {
  2188. return;
  2189. }
  2190. const audioArray = [];
  2191. let totalDuration = 0;
  2192. // 逐个处理文本项,支持长文本分割
  2193. for (let i = 0; i < textItems.length; i++) {
  2194. const item = textItems[i];
  2195. try {
  2196. // 使用分批次请求音频
  2197. const batchResult = await this.requestAudioInBatches(item.content, this.localVoiceId);
  2198. // 检查请求是否被取消
  2199. if (batchResult === null) {
  2200. return;
  2201. }
  2202. if (batchResult.audioSegments.length > 0) {
  2203. // 将所有音频段添加到音频数组
  2204. for (const segment of batchResult.audioSegments) {
  2205. if (!segment.error) {
  2206. audioArray.push({
  2207. isLead: item.isLead,
  2208. url: segment.url,
  2209. text: segment.text,
  2210. duration: segment.duration,
  2211. startIndex: segment.startIndex,
  2212. endIndex: segment.endIndex,
  2213. segmentIndex: segment.segmentIndex,
  2214. originalTextIndex: i, // 标记属于哪个原始文本项
  2215. isSegmented: batchResult.audioSegments.length > 1 // 标记是否为分段音频
  2216. });
  2217. totalDuration += segment.duration;
  2218. }
  2219. }
  2220. console.log(`${pageIndex + 1}页第${i + 1}个文本项预加载完成,获得 ${batchResult.audioSegments.filter(s => !s.error).length} 个音频段`);
  2221. } else {
  2222. console.error(`${pageIndex + 1}页第${i + 1}个文本项音频预加载全部失败`);
  2223. }
  2224. } catch (error) {
  2225. console.error(`${pageIndex + 1}页第${i + 1}个文本项处理异常:`, error);
  2226. }
  2227. // 每个文本项处理之间间隔150ms,避免请求过于频繁
  2228. if (i < textItems.length - 1) {
  2229. await new Promise(resolve => setTimeout(resolve, 150));
  2230. }
  2231. }
  2232. // 保存到缓存
  2233. if (audioArray.length > 0) {
  2234. this.audioCache[cacheKey] = {
  2235. audios: audioArray,
  2236. totalDuration: totalDuration,
  2237. voiceId: this.localVoiceId, // 保存音色ID用于验证
  2238. timestamp: Date.now() // 保存时间戳
  2239. };
  2240. // 限制缓存大小
  2241. this.limitCacheSize(1000);
  2242. }
  2243. },
  2244. // 检查指定页面是否有音频缓存
  2245. checkAudioCache(pageNumber) {
  2246. const cacheKey = `${this.courseId}_${pageNumber}_${this.localVoiceId}`;
  2247. const cachedData = this.audioCache[cacheKey];
  2248. if (cachedData && cachedData.audios && cachedData.audios.length > 0) {
  2249. return true;
  2250. }
  2251. return false;
  2252. },
  2253. // 自动播放已缓存的音频
  2254. async autoPlayCachedAudio() {
  2255. try {
  2256. // 如果正在音色切换中,不自动播放
  2257. if (this.isVoiceChanging) {
  2258. return;
  2259. }
  2260. const cacheKey = `${this.courseId}_${this.currentPage}_${this.voiceId}`;
  2261. const cachedData = this.audioCache[cacheKey];
  2262. if (!cachedData || !cachedData.audios || cachedData.audios.length === 0) {
  2263. return;
  2264. }
  2265. // 停止当前播放的音频
  2266. this.pauseAudio();
  2267. // 设置当前页面的音频数据
  2268. this.currentPageAudios = cachedData.audios;
  2269. this.totalDuration = cachedData.totalDuration;
  2270. // 查找第一个非导语音频
  2271. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  2272. this.currentAudioIndex = firstNonLeadIndex;
  2273. this.currentTime = 0;
  2274. this.isPlaying = false;
  2275. console.log(`🎵 autoPlayCachedAudio: 设置起始索引为${this.currentAudioIndex}(跳过导语)`);
  2276. // 如果所有音频都是导语,不播放
  2277. if (firstNonLeadIndex < 0) {
  2278. console.log('🎵 autoPlayCachedAudio: 所有音频都是导语,不播放');
  2279. return;
  2280. }
  2281. // 延迟一下再开始播放,确保UI更新完成
  2282. setTimeout(() => {
  2283. this.playAudio();
  2284. }, 300);
  2285. } catch (error) {
  2286. console.error('自动播放缓存音频失败:', error);
  2287. }
  2288. },
  2289. // 清理audioManager事件监听
  2290. removeAudioManagerListeners() {
  2291. if (this.audioManagerListeners) {
  2292. audioManager.off('play', this.audioManagerListeners.onPlay);
  2293. audioManager.off('pause', this.audioManagerListeners.onPause);
  2294. audioManager.off('ended', this.audioManagerListeners.onEnded);
  2295. audioManager.off('error', this.audioManagerListeners.onError);
  2296. audioManager.off('timeupdate', this.audioManagerListeners.onTimeupdate);
  2297. this.audioManagerListeners = null;
  2298. }
  2299. },
  2300. // 初始化audioManager事件监听
  2301. initAudioManagerListeners() {
  2302. // 先清理已有的监听器
  2303. this.removeAudioManagerListeners();
  2304. // 创建监听器对象,保存引用以便后续清理
  2305. this.audioManagerListeners = {
  2306. onPlay: (data) => {
  2307. if (data && data.audioType === 'sentence') {
  2308. this.isPlaying = true;
  2309. console.log('🎵 句子音频开始播放');
  2310. // 播放开始时立即更新高亮
  2311. this.updateHighlightIndex();
  2312. }
  2313. },
  2314. onPause: (data) => {
  2315. if (data && data.audioType === 'sentence') {
  2316. this.isPlaying = false;
  2317. console.log('⏸️ 句子音频暂停');
  2318. }
  2319. },
  2320. onEnded: (data) => {
  2321. if (data && data.audioType === 'sentence') {
  2322. this.isPlaying = false;
  2323. console.log('✅ 句子音频播放结束');
  2324. // 自动播放下一个音频
  2325. this.onAudioEnded();
  2326. }
  2327. },
  2328. onError: (data) => {
  2329. if (data && data.audioType === 'sentence') {
  2330. this.isPlaying = false;
  2331. console.error('❌ 句子音频播放错误:', data.error);
  2332. uni.showToast({
  2333. title: '音频播放失败',
  2334. icon: 'none'
  2335. });
  2336. }
  2337. },
  2338. onTimeupdate: (data) => {
  2339. if (data.audioType === 'sentence') {
  2340. // 计算总时间(包括之前音频的时长)
  2341. let totalTime = 0;
  2342. for (let i = 0; i < this.currentAudioIndex; i++) {
  2343. totalTime += this.currentPageAudios[i].duration;
  2344. }
  2345. totalTime += data.currentTime;
  2346. this.currentTime = totalTime;
  2347. // 如果不是正在拖動滑動條,則同步更新滑動條的值
  2348. if (!this.isDragging) {
  2349. this.sliderValue = this.currentTime;
  2350. }
  2351. }
  2352. }
  2353. };
  2354. // 绑定事件监听器
  2355. audioManager.on('play', this.audioManagerListeners.onPlay);
  2356. audioManager.on('pause', this.audioManagerListeners.onPause);
  2357. audioManager.on('ended', this.audioManagerListeners.onEnded);
  2358. audioManager.on('error', this.audioManagerListeners.onError);
  2359. audioManager.on('timeupdate', this.audioManagerListeners.onTimeupdate);
  2360. }
  2361. },
  2362. mounted() {
  2363. console.log('⚙️ 初始倍速配置:', {
  2364. 默認播放速度: this.playSpeed + 'x',
  2365. 可選速度選項: this.speedOptions.map(s => s + 'x'),
  2366. 初始支持狀態: this.playbackRateSupported
  2367. });
  2368. // 初始檢測播放速度支持
  2369. this.checkInitialPlaybackRateSupport();
  2370. // 从audioManager获取全局语速设置,如果存在则同步到本地
  2371. const globalPlaybackRate = audioManager.getGlobalPlaybackRate();
  2372. if (globalPlaybackRate && globalPlaybackRate !== this.playSpeed) {
  2373. this.playSpeed = globalPlaybackRate;
  2374. } else {
  2375. // 同步初始语速设置到audioManager
  2376. audioManager.setGlobalPlaybackRate(this.playSpeed);
  2377. }
  2378. // 初始化audioManager事件监听
  2379. this.initAudioManagerListeners();
  2380. },
  2381. // 自动播放预加载的音频
  2382. async autoPlayPreloadedAudio() {
  2383. try {
  2384. // 如果正在音色切换中,不自动播放
  2385. if (this.isVoiceChanging) {
  2386. return;
  2387. }
  2388. // 检查是否有音频数据
  2389. if (!this.hasAudioData || this.currentPageAudios.length === 0) {
  2390. return;
  2391. }
  2392. // 查找第一个非导语音频
  2393. const firstNonLeadIndex = this.findFirstNonLeadAudio();
  2394. if (firstNonLeadIndex < 0 || firstNonLeadIndex >= this.currentPageAudios.length) {
  2395. console.warn('🎵 autoPlayPreloadedAudio: 找不到有效的非导语音频');
  2396. return;
  2397. }
  2398. const firstAudio = this.currentPageAudios[firstNonLeadIndex];
  2399. if (!firstAudio || !firstAudio.url) {
  2400. console.warn('🎵 autoPlayPreloadedAudio: 第一个非导语音频数据无效');
  2401. return;
  2402. }
  2403. // 设置播放状态(跳过导语)
  2404. this.currentAudioIndex = firstNonLeadIndex;
  2405. this.currentTime = 0;
  2406. this.sliderValue = 0;
  2407. // 设置高亮索引
  2408. const highlightIndex = firstAudio.originalTextIndex !== undefined ? firstAudio.originalTextIndex : firstNonLeadIndex;
  2409. this.currentHighlightIndex = highlightIndex;
  2410. console.log(`🎵 autoPlayPreloadedAudio: 播放第一个非导语音频,索引=${firstNonLeadIndex}, isLead=${firstAudio.isLead}`);
  2411. // 使用audioManager播放第一个非导语音频
  2412. audioManager.playAudio(firstAudio.url, 'sentence', { playbackRate: this.playSpeed });
  2413. this.isPlaying = true;
  2414. } catch (error) {
  2415. console.error('自动播放预加载音频失败:', error);
  2416. }
  2417. },
  2418. beforeDestroy() {
  2419. // 清理页面切换防抖定时器
  2420. if (this.pageChangeTimer) {
  2421. clearTimeout(this.pageChangeTimer);
  2422. this.pageChangeTimer = null;
  2423. }
  2424. // 清理音频资源
  2425. this.destroyAudio();
  2426. // 清理audioManager事件监听器
  2427. this.removeAudioManagerListeners();
  2428. }
  2429. }
  2430. </script>
  2431. <style lang="scss" scoped>
  2432. /* 音频控制栏样式 */
  2433. .audio-controls-wrapper {
  2434. position: relative;
  2435. z-index: 10;
  2436. }
  2437. .audio-controls {
  2438. background: #fff;
  2439. padding: 20rpx 40rpx;
  2440. border-bottom: 1rpx solid #eee;
  2441. transition: transform 0.3s ease;
  2442. position: relative;
  2443. z-index: 10;
  2444. &.audio-hidden {
  2445. transform: translateY(100%);
  2446. }
  2447. }
  2448. .audio-time {
  2449. display: flex;
  2450. align-items: center;
  2451. margin-bottom: 20rpx;
  2452. }
  2453. .time-text {
  2454. font-size: 28rpx;
  2455. color: #999;
  2456. min-width: 80rpx;
  2457. }
  2458. .progress-container {
  2459. flex: 1;
  2460. margin: 0 20rpx;
  2461. }
  2462. .audio-controls-row {
  2463. display: flex;
  2464. align-items: center;
  2465. justify-content: space-between;
  2466. }
  2467. .control-btn {
  2468. display: flex;
  2469. align-items: center;
  2470. padding: 10rpx;
  2471. gap: 8rpx;
  2472. }
  2473. .control-btn.disabled {
  2474. pointer-events: none;
  2475. opacity: 0.6;
  2476. }
  2477. .control-text {
  2478. font-size: 28rpx;
  2479. color: #4A4A4A;
  2480. }
  2481. .play-btn {
  2482. display: flex;
  2483. align-items: center;
  2484. justify-content: center;
  2485. padding: 10rpx;
  2486. }
  2487. /* 音频加载状态样式 */
  2488. .audio-loading-container {
  2489. background: #fff;
  2490. padding: 40rpx;
  2491. border-bottom: 1rpx solid #eee;
  2492. display: flex;
  2493. flex-direction: column;
  2494. align-items: center;
  2495. justify-content: center;
  2496. gap: 20rpx;
  2497. position: relative;
  2498. z-index: 10;
  2499. }
  2500. /* 加载指示器样式 */
  2501. .loading-indicator {
  2502. display: flex;
  2503. align-items: center;
  2504. justify-content: center;
  2505. gap: 10rpx;
  2506. padding: 10rpx 20rpx;
  2507. background: rgba(6, 218, 220, 0.1);
  2508. border-radius: 20rpx;
  2509. margin-bottom: 10rpx;
  2510. }
  2511. .loading-indicator-text {
  2512. font-size: 24rpx;
  2513. color: #06DADC;
  2514. }
  2515. .loading-text {
  2516. font-size: 28rpx;
  2517. color: #999;
  2518. }
  2519. /* 音色切换加载状态特殊样式 */
  2520. .voice-changing {
  2521. background: linear-gradient(135deg, #fff5f0 0%, #ffe7d9 100%);
  2522. border: 2rpx solid #ff6b35;
  2523. }
  2524. .voice-changing-text {
  2525. color: #ff6b35;
  2526. font-weight: 500;
  2527. }
  2528. /* 预加载状态特殊样式 */
  2529. .preloading {
  2530. background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  2531. border: 2rpx solid #06DADC;
  2532. }
  2533. .preloading .loading-text {
  2534. color: #06DADC;
  2535. font-weight: 500;
  2536. }
  2537. /* 课程切换状态特殊样式 */
  2538. .course-switching {
  2539. background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  2540. border: 2rpx solid #52c41a;
  2541. }
  2542. .course-switching .loading-text {
  2543. color: #52c41a;
  2544. font-weight: 500;
  2545. }
  2546. /* 获取音频按钮样式 */
  2547. .audio-get-button-container {
  2548. background: rgba(255, 255, 255, 0.95);
  2549. backdrop-filter: blur(10px);
  2550. padding: 30rpx;
  2551. border-radius: 20rpx;
  2552. border: 2rpx solid #E5E5E5;
  2553. transition: all 0.3s ease;
  2554. position: relative;
  2555. z-index: 10;
  2556. }
  2557. .get-audio-btn {
  2558. display: flex;
  2559. align-items: center;
  2560. justify-content: center;
  2561. gap: 16rpx;
  2562. padding: 20rpx 40rpx;
  2563. background: linear-gradient(135deg, #06DADC 0%, #04B8BA 100%);
  2564. border-radius: 50rpx;
  2565. box-shadow: 0 8rpx 20rpx rgba(6, 218, 220, 0.3);
  2566. transition: all 0.3s ease;
  2567. }
  2568. .get-audio-btn:active {
  2569. transform: scale(0.95);
  2570. box-shadow: 0 4rpx 10rpx rgba(6, 218, 220, 0.2);
  2571. }
  2572. /* 音频预加载提示样式 */
  2573. .audio-preloaded-container {
  2574. display: flex;
  2575. justify-content: center;
  2576. align-items: center;
  2577. padding: 20rpx;
  2578. transition: all 0.3s ease;
  2579. position: relative;
  2580. z-index: 10;
  2581. }
  2582. .preloaded-tip {
  2583. display: flex;
  2584. align-items: center;
  2585. justify-content: center;
  2586. gap: 16rpx;
  2587. padding: 20rpx 40rpx;
  2588. background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  2589. border-radius: 50rpx;
  2590. box-shadow: 0 8rpx 20rpx rgba(82, 196, 26, 0.3);
  2591. transition: all 0.3s ease;
  2592. }
  2593. .preloaded-text {
  2594. color: #ffffff;
  2595. font-size: 28rpx;
  2596. font-weight: 500;
  2597. }
  2598. /* 音频获取失败样式 */
  2599. .audio-failed-container {
  2600. display: flex;
  2601. flex-direction: column;
  2602. align-items: center;
  2603. justify-content: center;
  2604. padding: 20rpx;
  2605. gap: 20rpx;
  2606. }
  2607. .failed-tip {
  2608. display: flex;
  2609. align-items: center;
  2610. justify-content: center;
  2611. gap: 16rpx;
  2612. padding: 20rpx 40rpx;
  2613. background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
  2614. border-radius: 50rpx;
  2615. box-shadow: 0 8rpx 20rpx rgba(255, 77, 79, 0.3);
  2616. }
  2617. .failed-text {
  2618. color: #ffffff;
  2619. font-size: 28rpx;
  2620. font-weight: 500;
  2621. }
  2622. .retry-btn {
  2623. display: flex;
  2624. align-items: center;
  2625. justify-content: center;
  2626. gap: 12rpx;
  2627. padding: 16rpx 32rpx;
  2628. background: linear-gradient(135deg, #06DADC 0%, #05B8BA 100%);
  2629. border-radius: 40rpx;
  2630. box-shadow: 0 6rpx 16rpx rgba(6, 218, 220, 0.3);
  2631. transition: all 0.3s ease;
  2632. }
  2633. .retry-btn:active {
  2634. transform: scale(0.95);
  2635. box-shadow: 0 4rpx 12rpx rgba(6, 218, 220, 0.4);
  2636. }
  2637. .retry-text {
  2638. color: #ffffff;
  2639. font-size: 26rpx;
  2640. font-weight: 500;
  2641. }
  2642. .get-audio-text {
  2643. font-size: 32rpx;
  2644. color: #FFFFFF;
  2645. font-weight: 500;
  2646. }
  2647. /* 会员限制容器样式 */
  2648. .member-restricted-container {
  2649. height: 0;
  2650. overflow: hidden;
  2651. opacity: 0;
  2652. pointer-events: none;
  2653. }
  2654. </style>