Skip to content

Instantly share code, notes, and snippets.

@iRi-E
Created December 9, 2023 17:40
Show Gist options
  • Save iRi-E/7fda94a3cd36ba2ef9e92bb99a33cf4a to your computer and use it in GitHub Desktop.
Save iRi-E/7fda94a3cd36ba2ef9e92bb99a33cf4a to your computer and use it in GitHub Desktop.
Userscript that reduces the sound of YouTube video ads and can also change their playback speed
// ==UserScript==
// @name YouTube Mute Ads
// @namespace https://gist.github.com/iRi-E
// @version 0.1
// @description Reduce the sound of YouTube video ads
// @author iRi_E
// @license MIT
// @match https://www.youtube.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @grant none
// ==/UserScript==
const volumeRatio = 0.1; // Ratio of volume of video ads to main video
const playbackSpeed = 0; // If not positive, use the same playback speed as main video
(function() {
'use strict';
let player = null;
let videoAds = null;
let savedVolume = null;
function findVideoAds(observer) {
videoAds = player.querySelector(':scope > .video-ads');
if (videoAds) {
observer.observe(videoAds, { childList: true });
console.log('[YMA] Found video ads');
}
return videoAds;
}
function onVideoAdsChange() {
if (videoAds.childNodes.length) {
if (!Number.isFinite(savedVolume)) {
savedVolume = player.getVolume();
player.setVolume(savedVolume * volumeRatio);
console.log('[YMA] Volume x ' + volumeRatio);
const speed = playbackSpeed > 0 ? playbackSpeed : player.getPlaybackRate();
if (speed != 1) {
player.querySelector('video').playbackRate = speed;
console.log('[YMA] Set playback rate ' + speed);
}
}
} else if (Number.isFinite(savedVolume)) {
player.setVolume(savedVolume);
savedVolume = null;
console.log('[YMA] Restore volume');
}
}
const observer = new MutationObserver(() => {
if (videoAds || findVideoAds(observer)) {
onVideoAdsChange();
}
});
const timer = setInterval(() => {
player = document.getElementById('movie_player');
if (player) {
clearInterval(timer);
if (findVideoAds(observer)) {
onVideoAdsChange();
} else {
observer.observe(player, { childList: true });
}
console.log('[YMA] Observer started');
}
}, 1000);
console.log('[YMA] Waiting for player to load...');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment