audio.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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, voice: string | 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.voice = voice
  30. this.callback = callback
  31. // Compatible with iphone ios17 ManagedMediaSource
  32. const MediaSource = window.MediaSource || window.ManagedMediaSource
  33. if (!MediaSource) {
  34. Toast.notify({
  35. message: 'Your browser does not support audio streaming, if you are using an iPhone, please update to iOS 17.1 or later.',
  36. type: 'error',
  37. })
  38. }
  39. this.mediaSource = MediaSource ? new MediaSource() : null
  40. this.audio = new Audio()
  41. this.setCallback(callback)
  42. this.audio.src = this.mediaSource ? URL.createObjectURL(this.mediaSource) : ''
  43. this.audio.autoplay = true
  44. const source = this.audioContext.createMediaElementSource(this.audio)
  45. source.connect(this.audioContext.destination)
  46. this.listenMediaSource('audio/mpeg')
  47. }
  48. public resetMsgId(msgId: string) {
  49. this.msgId = msgId
  50. }
  51. private listenMediaSource(contentType: string) {
  52. this.mediaSource?.addEventListener('sourceopen', () => {
  53. if (this.sourceBuffer)
  54. return
  55. this.sourceBuffer = this.mediaSource?.addSourceBuffer(contentType)
  56. })
  57. }
  58. public setCallback(callback: ((event: string) => {}) | null) {
  59. this.callback = callback
  60. if (callback) {
  61. this.audio.addEventListener('ended', () => {
  62. callback('ended')
  63. }, false)
  64. this.audio.addEventListener('paused', () => {
  65. callback('paused')
  66. }, true)
  67. this.audio.addEventListener('loaded', () => {
  68. callback('loaded')
  69. }, true)
  70. this.audio.addEventListener('play', () => {
  71. callback('play')
  72. }, true)
  73. this.audio.addEventListener('timeupdate', () => {
  74. callback('timeupdate')
  75. }, true)
  76. this.audio.addEventListener('loadeddate', () => {
  77. callback('loadeddate')
  78. }, true)
  79. this.audio.addEventListener('canplay', () => {
  80. callback('canplay')
  81. }, true)
  82. this.audio.addEventListener('error', () => {
  83. callback('error')
  84. }, true)
  85. }
  86. }
  87. private async loadAudio() {
  88. try {
  89. const audioResponse: any = await textToAudioStream(this.url, this.isPublic, { content_type: 'audio/mpeg' }, {
  90. message_id: this.msgId,
  91. streaming: true,
  92. voice: this.voice,
  93. text: this.msgContent,
  94. })
  95. if (audioResponse.status !== 200) {
  96. this.isLoadData = false
  97. if (this.callback)
  98. this.callback('error')
  99. }
  100. const reader = audioResponse.body.getReader()
  101. while (true) {
  102. const { value, done } = await reader.read()
  103. if (done) {
  104. this.receiveAudioData(value)
  105. break
  106. }
  107. this.receiveAudioData(value)
  108. }
  109. }
  110. catch (error) {
  111. this.isLoadData = false
  112. this.callback && this.callback('error')
  113. }
  114. }
  115. // play audio
  116. public playAudio() {
  117. if (this.isLoadData) {
  118. if (this.audioContext.state === 'suspended') {
  119. this.audioContext.resume().then((_) => {
  120. this.audio.play()
  121. this.callback && this.callback('play')
  122. })
  123. }
  124. else if (this.audio.ended) {
  125. this.audio.play()
  126. this.callback && this.callback('play')
  127. }
  128. if (this.callback)
  129. this.callback('play')
  130. }
  131. else {
  132. this.isLoadData = true
  133. this.loadAudio()
  134. }
  135. }
  136. private theEndOfStream() {
  137. const endTimer = setInterval(() => {
  138. if (!this.sourceBuffer?.updating) {
  139. this.mediaSource?.endOfStream()
  140. clearInterval(endTimer)
  141. }
  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. }, 10)
  155. }
  156. public async playAudioWithAudio(audio: string, play = true) {
  157. if (!audio || !audio.length) {
  158. this.finishStream()
  159. return
  160. }
  161. const audioContent = Buffer.from(audio, 'base64')
  162. this.receiveAudioData(new Uint8Array(audioContent))
  163. if (play) {
  164. this.isLoadData = true
  165. if (this.audio.paused) {
  166. this.audioContext.resume().then((_) => {
  167. this.audio.play()
  168. this.callback && this.callback('play')
  169. })
  170. }
  171. else if (this.audio.ended) {
  172. this.audio.play()
  173. this.callback && this.callback('play')
  174. }
  175. else if (this.audio.played) { /* empty */ }
  176. else {
  177. this.audio.play()
  178. this.callback && this.callback('play')
  179. }
  180. }
  181. }
  182. public pauseAudio() {
  183. this.callback && this.callback('paused')
  184. this.audio.pause()
  185. this.audioContext.suspend()
  186. }
  187. private cancer() {
  188. }
  189. private receiveAudioData(unit8Array: Uint8Array) {
  190. if (!unit8Array) {
  191. this.finishStream()
  192. return
  193. }
  194. const audioData = this.byteArrayToArrayBuffer(unit8Array)
  195. if (!audioData.byteLength) {
  196. if (this.mediaSource?.readyState === 'open')
  197. this.finishStream()
  198. return
  199. }
  200. if (this.sourceBuffer?.updating) {
  201. this.cacheBuffers.push(audioData)
  202. }
  203. else {
  204. if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
  205. this.cacheBuffers.push(audioData)
  206. const cacheBuffer = this.cacheBuffers.shift()!
  207. this.sourceBuffer?.appendBuffer(cacheBuffer)
  208. }
  209. else {
  210. this.sourceBuffer?.appendBuffer(audioData)
  211. }
  212. }
  213. }
  214. private byteArrayToArrayBuffer(byteArray: Uint8Array): ArrayBuffer {
  215. const arrayBuffer = new ArrayBuffer(byteArray.length)
  216. const uint8Array = new Uint8Array(arrayBuffer)
  217. uint8Array.set(byteArray)
  218. return arrayBuffer
  219. }
  220. }