Jeremy Kahn 94a4b2fb2e
refactor(services): Standardize services and lib organization (#226)
* refactor(Notification): use instance methods
* refactor(Audio): move to lib layer
* refactor(EncryptionService): rename instance to encryption
* refactor(ConnectionTest): move to lib
* refactor(FileTransfer): move to lib
* refactor(PeerRoom): move to lib
* refactor(sleep): move to lib
* refactor(type-guards): move to lib
* refactor(SerializationService): use standard instance name
* refactor(SettingsService): use standard instance name
2024-01-28 20:46:59 -06:00

34 lines
835 B
TypeScript

export class Audio {
private audioContext: AudioContext = new AudioContext()
private audioBuffer: AudioBuffer | null = null
constructor(audioDataUrl?: string) {
if (audioDataUrl) {
this.load(audioDataUrl)
}
}
load = async (audioDataUrl: string) => {
try {
const response = await fetch(audioDataUrl)
const arrayBuffer = await response.arrayBuffer()
this.audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer)
} catch (e) {
console.error(e)
}
}
play = () => {
if (this.audioBuffer === null) {
console.error('Audio buffer not available')
return
}
const audioSource = this.audioContext.createBufferSource()
audioSource.buffer = this.audioBuffer
audioSource.connect(this.audioContext.destination)
audioSource.start()
}
}