audio.player.manager.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import AudioPlayer from '@/app/components/base/audio-btn/audio'
  2. declare global {
  3. // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
  4. interface AudioPlayerManager {
  5. instance: AudioPlayerManager
  6. }
  7. }
  8. export class AudioPlayerManager {
  9. private static instance: AudioPlayerManager
  10. private audioPlayers: AudioPlayer | null = null
  11. private msgId: string | undefined
  12. private constructor() {
  13. }
  14. public static getInstance(): AudioPlayerManager {
  15. if (!AudioPlayerManager.instance) {
  16. AudioPlayerManager.instance = new AudioPlayerManager()
  17. this.instance = AudioPlayerManager.instance
  18. }
  19. return AudioPlayerManager.instance
  20. }
  21. public getAudioPlayer(url: string, isPublic: boolean, id: string | undefined, msgContent: string | null | undefined, voice: string | undefined, callback: ((event: string) => {}) | null): AudioPlayer {
  22. if (this.msgId && this.msgId === id && this.audioPlayers) {
  23. this.audioPlayers.setCallback(callback)
  24. return this.audioPlayers
  25. }
  26. else {
  27. if (this.audioPlayers) {
  28. try {
  29. this.audioPlayers.pauseAudio()
  30. this.audioPlayers.cacheBuffers = []
  31. this.audioPlayers.sourceBuffer?.abort()
  32. }
  33. catch (e) {
  34. }
  35. }
  36. this.msgId = id
  37. this.audioPlayers = new AudioPlayer(url, isPublic, id, msgContent, voice, callback)
  38. return this.audioPlayers
  39. }
  40. }
  41. public resetMsgId(msgId: string) {
  42. this.msgId = msgId
  43. this.audioPlayers?.resetMsgId(msgId)
  44. }
  45. }