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

3129 lines
114 KiB

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