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

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