audio.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. })
  56. }
  57. public setCallback(callback: ((event: string) => {}) | null) {
  58. this.callback = callback
  59. if (callback) {
  60. this.audio.addEventListener('ended', () => {
  61. callback('ended')
  62. }, false)
  63. this.audio.addEventListener('paused', () => {
  64. callback('paused')
  65. }, true)
  66. this.audio.addEventListener('loaded', () => {
  67. callback('loaded')
  68. }, true)
  69. this.audio.addEventListener('play', () => {
  70. callback('play')
  71. }, true)
  72. this.audio.addEventListener('timeupdate', () => {
  73. callback('timeupdate')
  74. }, true)
  75. this.audio.addEventListener('loadeddate', () => {
  76. callback('loadeddate')
  77. }, true)
  78. this.audio.addEventListener('canplay', () => {
  79. callback('canplay')
  80. }, true)
  81. this.audio.addEventListener('error', () => {
  82. callback('error')
  83. }, true)
  84. }
  85. }
  86. private async loadAudio() {
  87. try {
  88. const audioResponse: any = await textToAudioStream(this.url, this.isPublic, { content_type: 'audio/mpeg' }, {
  89. message_id: this.msgId,
  90. streaming: true,
  91. voice: this.voice,
  92. text: this.msgContent,
  93. })
  94. if (audioResponse.status !== 200) {
  95. this.isLoadData = false
  96. if (this.callback)
  97. this.callback('error')
  98. }
  99. const reader = audioResponse.body.getReader()
  100. while (true) {
  101. const { value, done } = await reader.read()
  102. if (done) {
  103. this.receiveAudioData(value)
  104. break
  105. }
  106. this.receiveAudioData(value)
  107. }
  108. }
  109. catch (error) {
  110. this.isLoadData = false
  111. this.callback && this.callback('error')
  112. }
  113. }
  114. // play audio
  115. public playAudio() {
  116. if (this.isLoadData) {
  117. if (this.audioContext.state === 'suspended') {
  118. this.audioContext.resume().then((_) => {
  119. this.audio.play()
  120. this.callback && this.callback('play')
  121. })
  122. }
  123. else if (this.audio.ended) {
  124. this.audio.play()
  125. this.callback && this.callback('play')
  126. }
  127. if (this.callback)
  128. this.callback('play')
  129. }
  130. else {
  131. this.isLoadData = true
  132. this.loadAudio()
  133. }
  134. }
  135. private theEndOfStream() {
  136. const endTimer = setInterval(() => {
  137. if (!this.sourceBuffer?.updating) {
  138. this.mediaSource?.endOfStream()
  139. clearInterval(endTimer)
  140. }
  141. console.log('finishStream endOfStream endTimer')
  142. }, 10)
  143. }
  144. private finishStream() {
  145. const timer = setInterval(() => {
  146. if (!this.cacheBuffers.length) {
  147. this.theEndOfStream()
  148. clearInterval(timer)
  149. }
  150. if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  151. const arrayBuffer = this.cacheBuffers.shift()!
  152. this.sourceBuffer?.appendBuffer(arrayBuffer)
  153. }
  154. console.log('finishStream timer')
  155. }, 10)
  156. }
  157. public async playAudioWithAudio(audio: string, play = true) {
  158. if (!audio || !audio.length) {
  159. this.finishStream()
  160. return
  161. }
  162. const audioContent = Buffer.from(audio, 'base64')
  163. this.receiveAudioData(new Uint8Array(audioContent))
  164. if (play) {
  165. this.isLoadData = true
  166. if (this.audio.paused) {
  167. this.audioContext.resume().then((_) => {
  168. this.audio.play()
  169. this.callback && this.callback('play')
  170. })
  171. }
  172. else if (this.audio.ended) {
  173. this.audio.play()
  174. this.callback && this.callback('play')
  175. }
  176. else if (this.audio.played) { /* empty */ }
  177. else {
  178. this.audio.play()
  179. this.callback && this.callback('play')
  180. }
  181. }
  182. }
  183. public pauseAudio() {
  184. this.callback && this.callback('paused')
  185. this.audio.pause()
  186. this.audioContext.suspend()
  187. }
  188. private cancer() {
  189. }
  190. private receiveAudioData(unit8Array: Uint8Array) {
  191. if (!unit8Array) {
  192. this.finishStream()
  193. return
  194. }
  195. const audioData = this.byteArrayToArrayBuffer(unit8Array)
  196. if (!audioData.byteLength) {
  197. if (this.mediaSource?.readyState === 'open')
  198. this.finishStream()
  199. return
  200. }
  201. if (this.sourceBuffer?.updating) {
  202. this.cacheBuffers.push(audioData)
  203. }
  204. else {
  205. if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  206. this.cacheBuffers.push(audioData)
  207. const cacheBuffer = this.cacheBuffers.shift()!
  208. this.sourceBuffer?.appendBuffer(cacheBuffer)
  209. }
  210. else {
  211. this.sourceBuffer?.appendBuffer(audioData)
  212. }
  213. }
  214. }
  215. private byteArrayToArrayBuffer(byteArray: Uint8Array): ArrayBuffer {
  216. const arrayBuffer = new ArrayBuffer(byteArray.length)
  217. const uint8Array = new Uint8Array(arrayBuffer)
  218. uint8Array.set(byteArray)
  219. return arrayBuffer
  220. }
  221. }