audio.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import Toast from '@/app/components/base/toast'
  2. import { textToAudioStream } from '@/service/share'
  3. declare global {
  4. // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
  5. interface Window {
  6. ManagedMediaSource: any
  7. }
  8. }
  9. export default class AudioPlayer {
  10. mediaSource: MediaSource | null
  11. audio: HTMLAudioElement
  12. audioContext: AudioContext
  13. sourceBuffer?: SourceBuffer
  14. cacheBuffers: ArrayBuffer[] = []
  15. pauseTimer: number | null = null
  16. msgId: string | undefined
  17. msgContent: string | null | undefined = null
  18. voice: string | undefined = undefined
  19. isLoadData = false
  20. url: string
  21. isPublic: boolean
  22. callback: ((event: string) => {}) | null
  23. constructor(streamUrl: string, isPublic: boolean, msgId: string | undefined, msgContent: string | null | undefined, callback: ((event: string) => {}) | null) {
  24. this.audioContext = new AudioContext()
  25. this.msgId = msgId
  26. this.msgContent = msgContent
  27. this.url = streamUrl
  28. this.isPublic = isPublic
  29. this.callback = callback
  30. // Compatible with iphone ios17 ManagedMediaSource
  31. const MediaSource = window.MediaSource || window.ManagedMediaSource
  32. if (!MediaSource) {
  33. Toast.notify({
  34. message: 'Your browser does not support audio streaming, if you are using an iPhone, please update to iOS 17.1 or later.',
  35. type: 'error',
  36. })
  37. }
  38. this.mediaSource = MediaSource ? new MediaSource() : null
  39. this.audio = new Audio()
  40. this.setCallback(callback)
  41. this.audio.src = this.mediaSource ? URL.createObjectURL(this.mediaSource) : ''
  42. this.audio.autoplay = true
  43. const source = this.audioContext.createMediaElementSource(this.audio)
  44. source.connect(this.audioContext.destination)
  45. this.listenMediaSource('audio/mpeg')
  46. }
  47. public resetMsgId(msgId: string) {
  48. this.msgId = msgId
  49. }
  50. private listenMediaSource(contentType: string) {
  51. this.mediaSource?.addEventListener('sourceopen', () => {
  52. if (this.sourceBuffer)
  53. return
  54. this.sourceBuffer = this.mediaSource?.addSourceBuffer(contentType)
  55. // this.sourceBuffer?.addEventListener('update', () => {
  56. // if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  57. // const cacheBuffer = this.cacheBuffers.shift()!
  58. // this.sourceBuffer?.appendBuffer(cacheBuffer)
  59. // }
  60. // // this.pauseAudio()
  61. // })
  62. //
  63. // this.sourceBuffer?.addEventListener('updateend', () => {
  64. // if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  65. // const cacheBuffer = this.cacheBuffers.shift()!
  66. // this.sourceBuffer?.appendBuffer(cacheBuffer)
  67. // }
  68. // // this.pauseAudio()
  69. // })
  70. })
  71. }
  72. public setCallback(callback: ((event: string) => {}) | null) {
  73. this.callback = callback
  74. if (callback) {
  75. this.audio.addEventListener('ended', () => {
  76. callback('ended')
  77. }, false)
  78. this.audio.addEventListener('paused', () => {
  79. callback('paused')
  80. }, true)
  81. this.audio.addEventListener('loaded', () => {
  82. callback('loaded')
  83. }, true)
  84. this.audio.addEventListener('play', () => {
  85. callback('play')
  86. }, true)
  87. this.audio.addEventListener('timeupdate', () => {
  88. callback('timeupdate')
  89. }, true)
  90. this.audio.addEventListener('loadeddate', () => {
  91. callback('loadeddate')
  92. }, true)
  93. this.audio.addEventListener('canplay', () => {
  94. callback('canplay')
  95. }, true)
  96. this.audio.addEventListener('error', () => {
  97. callback('error')
  98. }, true)
  99. }
  100. }
  101. private async loadAudio() {
  102. try {
  103. const audioResponse: any = await textToAudioStream(this.url, this.isPublic, { content_type: 'audio/mpeg' }, {
  104. message_id: this.msgId,
  105. streaming: true,
  106. voice: this.voice,
  107. text: this.msgContent,
  108. })
  109. if (audioResponse.status !== 200) {
  110. this.isLoadData = false
  111. if (this.callback)
  112. this.callback('error')
  113. }
  114. const reader = audioResponse.body.getReader()
  115. while (true) {
  116. const { value, done } = await reader.read()
  117. if (done) {
  118. this.receiveAudioData(value)
  119. break
  120. }
  121. this.receiveAudioData(value)
  122. }
  123. }
  124. catch (error) {
  125. this.isLoadData = false
  126. this.callback && this.callback('error')
  127. }
  128. }
  129. // play audio
  130. public playAudio() {
  131. if (this.isLoadData) {
  132. if (this.audioContext.state === 'suspended') {
  133. this.audioContext.resume().then((_) => {
  134. this.audio.play()
  135. this.callback && this.callback('play')
  136. })
  137. }
  138. else if (this.audio.ended) {
  139. this.audio.play()
  140. this.callback && this.callback('play')
  141. }
  142. if (this.callback)
  143. this.callback('play')
  144. }
  145. else {
  146. this.isLoadData = true
  147. this.loadAudio()
  148. }
  149. }
  150. private theEndOfStream() {
  151. const endTimer = setInterval(() => {
  152. if (!this.sourceBuffer?.updating) {
  153. this.mediaSource?.endOfStream()
  154. clearInterval(endTimer)
  155. }
  156. console.log('finishStream endOfStream endTimer')
  157. }, 10)
  158. }
  159. private finishStream() {
  160. const timer = setInterval(() => {
  161. if (!this.cacheBuffers.length) {
  162. this.theEndOfStream()
  163. clearInterval(timer)
  164. }
  165. if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  166. const arrayBuffer = this.cacheBuffers.shift()!
  167. this.sourceBuffer?.appendBuffer(arrayBuffer)
  168. }
  169. console.log('finishStream timer')
  170. }, 10)
  171. }
  172. public async playAudioWithAudio(audio: string, play = true) {
  173. if (!audio || !audio.length) {
  174. this.finishStream()
  175. return
  176. }
  177. const audioContent = Buffer.from(audio, 'base64')
  178. this.receiveAudioData(new Uint8Array(audioContent))
  179. if (play) {
  180. this.isLoadData = true
  181. if (this.audio.paused) {
  182. this.audioContext.resume().then((_) => {
  183. this.audio.play()
  184. this.callback && this.callback('play')
  185. })
  186. }
  187. else if (this.audio.ended) {
  188. this.audio.play()
  189. this.callback && this.callback('play')
  190. }
  191. else if (this.audio.played) { /* empty */ }
  192. else {
  193. this.audio.play()
  194. this.callback && this.callback('play')
  195. }
  196. }
  197. }
  198. public pauseAudio() {
  199. this.callback && this.callback('paused')
  200. this.audio.pause()
  201. this.audioContext.suspend()
  202. }
  203. private cancer() {
  204. }
  205. private receiveAudioData(unit8Array: Uint8Array) {
  206. if (!unit8Array) {
  207. this.finishStream()
  208. return
  209. }
  210. const audioData = this.byteArrayToArrayBuffer(unit8Array)
  211. if (!audioData.byteLength) {
  212. if (this.mediaSource?.readyState === 'open')
  213. this.finishStream()
  214. return
  215. }
  216. if (this.sourceBuffer?.updating) {
  217. this.cacheBuffers.push(audioData)
  218. }
  219. else {
  220. if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  221. this.cacheBuffers.push(audioData)
  222. const cacheBuffer = this.cacheBuffers.shift()!
  223. this.sourceBuffer?.appendBuffer(cacheBuffer)
  224. }
  225. else {
  226. this.sourceBuffer?.appendBuffer(audioData)
  227. }
  228. }
  229. }
  230. private byteArrayToArrayBuffer(byteArray: Uint8Array): ArrayBuffer {
  231. const arrayBuffer = new ArrayBuffer(byteArray.length)
  232. const uint8Array = new Uint8Array(arrayBuffer)
  233. uint8Array.set(byteArray)
  234. return arrayBuffer
  235. }
  236. }