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

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