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

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