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

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