audio.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { defineStore } from 'pinia';
  2. import { ref, computed } from 'vue';
  3. import { get, post, getFullUrl } from '../utils/request';
  4. import type { AudioItem, Voice, VoiceParams } from '../types';
  5. export const useAudioStore = defineStore('audio', () => {
  6. // 状态
  7. const voices = ref<Voice[]>([]);
  8. const currentAudio = ref<AudioItem | null>(null);
  9. const playlist = ref<AudioItem[]>([]);
  10. const currentIndex = ref(-1);
  11. const isPlaying = ref(false);
  12. const currentTime = ref(0);
  13. const duration = ref(0);
  14. const playRate = ref(1);
  15. // 播放模式: 'sequence' | 'loop' | 'single' | 'random'
  16. const playMode = ref<'sequence' | 'loop' | 'single' | 'random'>('sequence');
  17. // 音频上下文
  18. let audioContext: UniApp.InnerAudioContext | null = null;
  19. // 计算属性
  20. const hasPlaylist = computed(() => playlist.value.length > 0);
  21. const hasNext = computed(() => currentIndex.value < playlist.value.length - 1);
  22. const hasPrev = computed(() => currentIndex.value > 0);
  23. // 初始化音频上下文
  24. function initAudioContext() {
  25. if (audioContext) return;
  26. audioContext = uni.createInnerAudioContext();
  27. audioContext.onPlay(() => {
  28. isPlaying.value = true;
  29. });
  30. audioContext.onPause(() => {
  31. isPlaying.value = false;
  32. });
  33. audioContext.onEnded(() => {
  34. isPlaying.value = false;
  35. // 自动播放下一首
  36. if (hasNext.value) {
  37. playNext();
  38. } else {
  39. // 列表播放完毕,停止播放
  40. handlePlayMode();
  41. }
  42. });
  43. audioContext.onTimeUpdate(() => {
  44. currentTime.value = audioContext?.currentTime || 0;
  45. const d = audioContext?.duration || 0;
  46. // 只有当音频元数据时长合理(小于1小时)且当前显示时长异常(为0或异常大)时才更新
  47. if (d > 0 && d < 3600) {
  48. if (duration.value === 0 || duration.value > 3600 || Math.abs(duration.value - d) < 1) {
  49. duration.value = d;
  50. }
  51. }
  52. });
  53. audioContext.onError((err: any) => {
  54. console.error('音频播放错误:', err);
  55. console.error('错误码:', err.errCode);
  56. console.error('错误信息:', err.errMsg);
  57. isPlaying.value = false;
  58. // 尝试获取更详细的错误信息
  59. if (audioContext) {
  60. console.error('audioContext.src:', audioContext.src);
  61. console.error('audioContext.readyState:', audioContext.readyState);
  62. }
  63. });
  64. audioContext.onCanplay(() => {
  65. console.log('音频已准备好播放');
  66. });
  67. }
  68. // 获取音色列表
  69. async function fetchVoices() {
  70. const result = await get<{ voices: Voice[] }>('/tts/voices');
  71. voices.value = result.voices;
  72. return result.voices;
  73. }
  74. // 生成音频
  75. async function generateAudio(
  76. text: string,
  77. voiceId: string,
  78. voiceParams: VoiceParams
  79. ) {
  80. uni.showLoading({ title: '生成中...', mask: true });
  81. try {
  82. const result = await post<{
  83. audioId: string;
  84. audioUrl: string;
  85. duration: number;
  86. size: number;
  87. }>('/tts/generate', { text, voiceId, voiceParams });
  88. uni.hideLoading();
  89. return result;
  90. } catch (error) {
  91. uni.hideLoading();
  92. throw error;
  93. }
  94. }
  95. // 播放音频
  96. function play(audio: AudioItem) {
  97. initAudioContext();
  98. // 重置时长,避免切换书籍后显示旧时长
  99. currentTime.value = 0;
  100. duration.value = 0;
  101. currentAudio.value = audio;
  102. // 获取完整的音频 URL
  103. const fullUrl = getFullUrl(audio.audioUrl);
  104. console.log('播放音频:', audio.title, 'URL:', fullUrl, '时长:', audio.audioDuration);
  105. // 如果音频源相同,只切换播放状态
  106. if (audioContext && audioContext.src === fullUrl) {
  107. console.log('音频源相同,切换播放状态');
  108. audioContext.play();
  109. } else if (audioContext) {
  110. console.log('设置新音频源并播放:', fullUrl);
  111. audioContext.src = fullUrl;
  112. audioContext.play();
  113. } else {
  114. console.error('audioContext 未初始化!');
  115. }
  116. // 使用 API 返回的 audioDuration 作为初始时长(避免音频文件 metadata 错误的问题)
  117. if (audio.audioDuration && audio.audioDuration > 0 && audio.audioDuration < 3600) {
  118. duration.value = audio.audioDuration;
  119. }
  120. }
  121. // 暂停
  122. function pause() {
  123. if (audioContext) {
  124. audioContext.pause();
  125. }
  126. }
  127. // 继续播放
  128. function resume() {
  129. if (audioContext) {
  130. audioContext.play();
  131. }
  132. }
  133. // 切换播放/暂停
  134. function togglePlay() {
  135. if (isPlaying.value) {
  136. pause();
  137. } else {
  138. resume();
  139. }
  140. }
  141. // 播放上一首
  142. function playPrev() {
  143. if (hasPrev.value) {
  144. currentIndex.value--;
  145. play(playlist.value[currentIndex.value]);
  146. }
  147. }
  148. // 播放下一首
  149. function playNext() {
  150. if (hasNext.value) {
  151. currentIndex.value++;
  152. play(playlist.value[currentIndex.value]);
  153. }
  154. }
  155. // 处理播放模式
  156. function handlePlayMode() {
  157. if (playlist.value.length === 0) return;
  158. switch (playMode.value) {
  159. case 'single':
  160. // 单曲循环
  161. play(playlist.value[currentIndex.value]);
  162. break;
  163. case 'loop':
  164. // 列表循环
  165. if (currentIndex.value < playlist.value.length - 1) {
  166. playNext();
  167. } else {
  168. // 回到第一首
  169. currentIndex.value = 0;
  170. play(playlist.value[0]);
  171. }
  172. break;
  173. case 'random':
  174. // 随机播放
  175. const randomIndex = Math.floor(Math.random() * playlist.value.length);
  176. currentIndex.value = randomIndex;
  177. play(playlist.value[randomIndex]);
  178. break;
  179. case 'sequence':
  180. default:
  181. // 顺序播放(不自动播放)
  182. break;
  183. }
  184. }
  185. // 切换播放模式
  186. function togglePlayMode() {
  187. const modes: Array<'sequence' | 'loop' | 'single' | 'random'> = ['sequence', 'loop', 'single', 'random'];
  188. const currentIndex = modes.indexOf(playMode.value);
  189. playMode.value = modes[(currentIndex + 1) % modes.length];
  190. const modeNames = {
  191. sequence: '顺序播放',
  192. loop: '列表循环',
  193. single: '单曲循环',
  194. random: '随机播放',
  195. };
  196. uni.showToast({
  197. title: modeNames[playMode.value],
  198. icon: 'none',
  199. });
  200. }
  201. // 跳转到指定位置
  202. function seek(time: number) {
  203. if (audioContext) {
  204. audioContext.seek(time);
  205. currentTime.value = time;
  206. }
  207. }
  208. // 设置播放速度
  209. function setPlayRate(rate: number) {
  210. playRate.value = rate;
  211. if (audioContext) {
  212. audioContext.playbackRate = rate;
  213. }
  214. }
  215. // 设置播放列表
  216. function setPlaylist(list: AudioItem[], index: number = 0, autoPlay: boolean = true) {
  217. playlist.value = list;
  218. currentIndex.value = index;
  219. if (list.length > 0 && autoPlay) {
  220. play(list[index]);
  221. }
  222. }
  223. // 销毁音频上下文
  224. function destroy() {
  225. if (audioContext) {
  226. audioContext.destroy();
  227. audioContext = null;
  228. }
  229. }
  230. return {
  231. // 状态
  232. voices,
  233. currentAudio,
  234. playlist,
  235. currentIndex,
  236. isPlaying,
  237. currentTime,
  238. duration,
  239. playRate,
  240. playMode,
  241. // 计算属性
  242. hasPlaylist,
  243. hasNext,
  244. hasPrev,
  245. // 方法
  246. fetchVoices,
  247. generateAudio,
  248. play,
  249. pause,
  250. resume,
  251. togglePlay,
  252. playPrev,
  253. playNext,
  254. handlePlayMode,
  255. togglePlayMode,
  256. seek,
  257. setPlayRate,
  258. setPlaylist,
  259. destroy,
  260. };
  261. });