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

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