Skip to content

Commit

Permalink
Feat: [Envelope] allow passing an audio context (#3179)
Browse files Browse the repository at this point in the history
* Feat: [Envelope] allow passing an audio context

* Cache volume
  • Loading branch information
katspaugh authored Sep 9, 2023
1 parent 87192a8 commit 759b8a6
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/plugins/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type EnvelopePluginOptions = {
dragPointSize?: number
dragPointFill?: string
dragPointStroke?: string
audioContext?: AudioContext
}

const defaultOptions = {
Expand Down Expand Up @@ -254,6 +255,7 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
private throttleTimeout: ReturnType<typeof setTimeout> | null = null
private ac: AudioContext | null = null
private gain: GainNode['gain'] | null = null
private volume = 1

/**
* Create a new Envelope plugin.
Expand Down Expand Up @@ -324,24 +326,27 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
* Destroy the plugin instance.
*/
public destroy() {
if (this.ac && this.ac !== this.options.audioContext) {
this.ac.close()
}
this.polyline?.destroy()
this.ac?.close()
super.destroy()
}

/**
* Get the envelope volume.
*/
public getCurrentVolume(): number {
return this.gain?.value || 0
return this.volume
}

/**
* Set the envelope volume. 0..1 (more than 1 will boost the volume).
*/
public setVolume(floatValue: number) {
this.volume = floatValue
if (this.gain) {
this.gain.value = floatValue
this.gain.value = this.volume
}
}

Expand All @@ -355,6 +360,7 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
options.volume = options.volume ?? this.wavesurfer.getVolume()

this.initAudioContext(this.wavesurfer.getMediaElement())
this.setVolume(options.volume)

this.subscriptions.push(
this.wavesurfer.on('decode', (duration) => {
Expand Down Expand Up @@ -382,7 +388,7 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
}

private initAudioContext(mediaElement: HTMLMediaElement) {
const ac = new AudioContext()
const ac = this.options.audioContext || new AudioContext()
const gainNode = ac.createGain()
gainNode.gain.value = this.options.volume ?? 1
gainNode.connect(ac.destination)
Expand Down Expand Up @@ -466,7 +472,7 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti

if (roundedVolume !== this.getCurrentVolume()) {
this.setVolume(roundedVolume)
this.emit('volume-change', newVolume)
this.emit('volume-change', roundedVolume)
}
}
}
Expand Down

0 comments on commit 759b8a6

Please sign in to comment.