Skip to content

Commit

Permalink
[Envelope]: use media volume instead of Web Audio
Browse files Browse the repository at this point in the history
  • Loading branch information
katspaugh committed Sep 30, 2023
1 parent dfa5968 commit 8cc95ad
Showing 1 changed file with 1 addition and 30 deletions.
31 changes: 1 addition & 30 deletions src/plugins/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export type EnvelopePluginOptions = {
dragPointSize?: number
dragPointFill?: string
dragPointStroke?: string
audioContext?: AudioContext
}

const defaultOptions = {
Expand Down Expand Up @@ -253,8 +252,6 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
private polyline: Polyline | null = null
private points: EnvelopePoint[]
private throttleTimeout: ReturnType<typeof setTimeout> | null = null
private ac: AudioContext | null = null
private gain: GainNode['gain'] | null = null
private volume = 1

/**
Expand Down Expand Up @@ -326,9 +323,6 @@ 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()
super.destroy()
}
Expand All @@ -345,9 +339,7 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
*/
public setVolume(floatValue: number) {
this.volume = floatValue
if (this.gain) {
this.gain.value = this.volume
}
this.wavesurfer?.setVolume(floatValue)
}

/** Called by wavesurfer, don't call manually */
Expand All @@ -359,7 +351,6 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
const { options } = this
options.volume = options.volume ?? this.wavesurfer.getVolume()

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

this.subscriptions.push(
Expand All @@ -378,29 +369,9 @@ class EnvelopePlugin extends BasePlugin<EnvelopePluginEvents, EnvelopePluginOpti
this.wavesurfer.on('timeupdate', (time) => {
this.onTimeUpdate(time)
}),

this.wavesurfer.on('play', () => {
if (this.ac?.state === 'suspended') {
this.ac.resume()
}
}),
)
}

private initAudioContext(mediaElement: HTMLMediaElement) {
const ac = this.options.audioContext || new AudioContext()
const gainNode = ac.createGain()
gainNode.gain.value = this.options.volume ?? 1
gainNode.connect(ac.destination)

// Create a media element source
const source = ac.createMediaElementSource(mediaElement)
source.connect(gainNode)

this.ac = ac
this.gain = gainNode.gain
}

private emitPoints() {
if (this.throttleTimeout) {
clearTimeout(this.throttleTimeout)
Expand Down

0 comments on commit 8cc95ad

Please sign in to comment.