Skip to content

Commit

Permalink
♻️ Use GainNode API to update video volume. (#37491)
Browse files Browse the repository at this point in the history
* Use GainNode API to set video volume.

* Handle cross-browser differences when creating audio context.
  • Loading branch information
Alejandrina Patrón committed Feb 11, 2022
1 parent d0bf1b6 commit 37aac3c
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions extensions/amp-story/1.0/media-pool.js
Expand Up @@ -161,6 +161,18 @@ export class MediaPool {
*/
this.sources_ = {};

/**
* The audio context.
* @private {?AudioContext}
*/
this.audioContext_ = null;

/**
* Maps a media element's ID to its audio source.
* @private @const {!Object<string, !MediaElementAudioSourceNode>}
*/
this.audioSources_ = {};

/**
* Maps a media element's ID to the element. This is necessary, as elements
* are kept in memory when they are swapped out of the DOM.
Expand Down Expand Up @@ -854,9 +866,9 @@ export class MediaPool {
return Promise.resolve();
}

// When a video is muted, reset its volume to the default value of 1.
if (mediaType == MediaType.VIDEO) {
domMediaEl.volume = 1;
const audioSource = this.audioSources_[domMediaEl.id];
if (audioSource) {
audioSource.disconnect();
}

return this.enqueueMediaElementTask_(poolMediaEl, new MuteTask());
Expand Down Expand Up @@ -884,7 +896,25 @@ export class MediaPool {
if (ampVideoEl) {
const volume = ampVideoEl.getAttribute('volume');
if (volume) {
domMediaEl.volume = parseFloat(volume);
// Handle cross-browser differences (see https://googlechrome.github.io/samples/webaudio-method-chaining/).
if (typeof AudioContext === 'function') {
this.audioContext_ = this.audioContext_ || new AudioContext();
} else if (typeof webkitAudioContext === 'function') {
this.audioContext_ =
this.audioContext_ || new global.webkitAudioContext();
}

if (this.audioContext_) {
const audioSource =
this.audioSources_[domMediaEl.id] ||
this.audioContext_.createMediaElementSource(domMediaEl);
this.audioSources_[domMediaEl.id] = audioSource;
const gainNode = this.audioContext_.createGain();
gainNode.gain.value = parseFloat(volume);
audioSource
.connect(gainNode)
.connect(this.audioContext_.destination);
}
}
}
}
Expand Down

0 comments on commit 37aac3c

Please sign in to comment.