Skip to content

Commit

Permalink
Add disableAutoPause flag (#246)
Browse files Browse the repository at this point in the history
  • Loading branch information
bigtimebuddy authored May 31, 2023
1 parent 702da5b commit 69617cd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
16 changes: 16 additions & 0 deletions src/SoundLibrary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,22 @@ class SoundLibrary
: this._htmlAudioContext;
}

/**
* This disables auto-pause all playback when the window blurs (WebAudio only).
* This is helpful to keep from playing sounds when the user switches tabs.
* However, if you're running content within an iframe, this may be undesirable
* and you should disable (set to `true`) this behavior.
* @default false
*/
public get disableAutoPause(): boolean
{
return !this._webAudioContext.autoPause;
}
public set disableAutoPause(autoPause: boolean)
{
this._webAudioContext.autoPause = !autoPause;
}

/**
* Removes a sound by alias.
* @param alias - The sound alias reference.
Expand Down
19 changes: 14 additions & 5 deletions src/webaudio/WebAudioContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ class WebAudioContext extends Filterable implements IMediaContext
*/
private _locked: boolean;

/** The paused state when blurring the current window */
private _pausedOnBlur: boolean;

/** Set to false ignore suspending when window is blurred */
public autoPause = true;

constructor()
{
const win: any = window as any;
Expand Down Expand Up @@ -122,16 +128,19 @@ class WebAudioContext extends Filterable implements IMediaContext

if (state === 'suspended' || state === 'interrupted' || !this._locked)
{
this._ctx.resume();
this.paused = this._pausedOnBlur;
this.refreshPaused();
}
}

/** Handle mobile WebAudio context suspend */
private onBlur(): void
{
if (!this._locked)
if (!this._locked && this.autoPause)
{
this._ctx.suspend();
this._pausedOnBlur = this._paused;
this.paused = true;
this.refreshPaused();
}
}

Expand Down Expand Up @@ -263,11 +272,11 @@ class WebAudioContext extends Filterable implements IMediaContext
{
if (paused && this._ctx.state === 'running')
{
(this._ctx as any).suspend();
this._ctx.suspend();
}
else if (!paused && this._ctx.state === 'suspended')
{
(this._ctx as any).resume();
this._ctx.resume();
}
this._paused = paused;
}
Expand Down

0 comments on commit 69617cd

Please sign in to comment.