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.

89 lines
2.8 KiB

  1. import { defineStore } from 'pinia'
  2. export const useAudioStore = defineStore('audio', {
  3. state: () => ({
  4. soundInstance: null, // Howl 实例
  5. isPlaying: false, // 播放状态
  6. isVoiceEnabled: true, // 新增声音开关状态
  7. playbackPosition: 0, // 新增播放位置存储
  8. lastVoiceState: null,
  9. ttsUrl:'',
  10. isNewInstance: false, // 新增是否是新实例的标志
  11. nowSound:'',
  12. currentAudioUrl: '', // 当前音频URL
  13. isPaused: false, // 是否处于暂停状态
  14. duration: 0 // 音频总时长
  15. }),
  16. actions: {
  17. // 设置音频实例
  18. setAudioInstance(instance) {
  19. this.soundInstance = instance
  20. },
  21. // 播放控制
  22. play() {
  23. if (this.soundInstance) {
  24. if (this.isPaused && this.playbackPosition > 0) {
  25. // 从暂停位置继续播放
  26. this.soundInstance.seek(this.playbackPosition)
  27. }
  28. this.soundInstance.play()
  29. this.isPlaying = true
  30. this.isPaused = false
  31. }
  32. },
  33. // 暂停控制
  34. pause() {
  35. if (this.soundInstance && this.isPlaying) {
  36. // 保存当前播放位置
  37. this.playbackPosition = this.soundInstance.seek() || 0
  38. this.soundInstance.pause()
  39. this.isPlaying = false
  40. this.isPaused = true
  41. }
  42. },
  43. // 停止播放
  44. stop() {
  45. if (this.soundInstance) {
  46. this.soundInstance.stop()
  47. this.isPlaying = false
  48. this.isPaused = false
  49. this.playbackPosition = 0
  50. }
  51. },
  52. // 切换播放/暂停
  53. togglePlayPause() {
  54. if (this.isPlaying) {
  55. this.pause()
  56. } else {
  57. this.play()
  58. }
  59. },
  60. // 设置当前音频URL
  61. setCurrentAudioUrl(url) {
  62. if (this.currentAudioUrl !== url) {
  63. // 如果是新的音频,重置播放状态
  64. this.stop()
  65. this.currentAudioUrl = url
  66. this.playbackPosition = 0
  67. this.isPaused = false
  68. }
  69. },
  70. // 语音开关控制
  71. toggleVoice() {
  72. this.isVoiceEnabled = !this.isVoiceEnabled
  73. if (!this.isVoiceEnabled) {
  74. // 关闭语音时停止当前播放
  75. this.stop()
  76. }
  77. },
  78. // 重置音频状态
  79. resetAudioState() {
  80. this.stop()
  81. this.currentAudioUrl = ''
  82. this.ttsUrl = ''
  83. this.soundInstance = null
  84. this.nowSound = ''
  85. }
  86. }
  87. })