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

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