User:Blue-Haired Lawyer/ogg.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* play ogg sounds inline */
var soundElement;
var nowPlaying = 0;
var soundStopped;

function playPauseSound(evnt) {
	var e = window.event ? window.event : evnt;
	var obj = window.event ? window.event.srcElement : evnt.target;

  	// Search the tree to see id there's a link
	var depth = 0;
	while(obj && obj.parentNode && depth < 5) {
		if(obj.tagName == "A") {
			// Is this link a ogg file
			var m = obj.href.match(/\.([^\.\/]*)$/);
			if(!m) return true;
			var extension = m[1];
			if(extension != "ogg") return true;
			
			// just make sure this isn't a file descripted page
			if(obj.pathname.substr(0, 6) == "/wiki/") return true;
			
			// only act upon left clicks 
			if(e.which != 1) return true;
			
			// if user clicks on a sound during the playback
			// of another sound, pause the first
			if(soundElement.src != obj.href && nowPlaying == 1) {
				soundElement.pause();
				nowPlaying = 0;
			}
			
			// set up a new AUDIO tag when appropriate
			if(!soundElement.src || soundElement.src != obj.href) {
				soundElement = document.createElement("AUDIO");
				soundElement.src = obj.href;
				soundElement.addEventListener("pause", soundStopped); 
				soundElement.addEventListener("ended", soundStopped); 
			}
			
			// play or pause as appropriate
			if(nowPlaying == 1) {
				soundElement.pause();
			} else {
				soundElement.play();
				nowPlaying = 1;
			}
						
			if (typeof e.preventDefault != 'undefined') {
				e.preventDefault();
			} else {
				e.returnValue = false;
			}
		
			return false;
		}

		obj = obj.parentNode;
		depth++;
	}
}

function soundStopped() {
	nowPlaying = 0;
}


// Does this browser support the audio element and play ogg sounds?
var soundElement = document.createElement("AUDIO");
if(soundElement.play && soundElement.canPlayType) {
	var canPlay = soundElement.canPlayType('application/ogg');
	if(canPlay != "no" && canPlay != "") {
		document.addEventListener("click", playPauseSound);
	}
}