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.
// Superseded by: https://en.wiki.x.io/wiki/User:IagoQnsi/ipareader

// Adds buttons next to IPA to speak using the default TTS

// Verdict: doesn't work so well. OS TTS engines aren't that good, especially
//          for IPA. They can't read many of the special characters or completely
//          elide them, resulting in an incorrect pronunciation. A tool like this
//          is only useful if it works. Works somewhat okay for just IPA-en but
//          that's usually where they're least-needed.

// License: CC0

// Make configurable via an object in user's common.js?
// References:
//     https://caniuse.com/#feat=speech-synthesis
//     https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis
//     https://mdn.github.io/web-speech-api/speak-easy-synthesis/ (demo)

// Need a waveform icon to distinguish from speaker used for actual voice samples

function attachSpeaker() {
	ipaString = $(this).text();
	
	// Make sure it's an IPA transcription bookended by slashes or square brackets
	if (/^[^/[]/.test(ipaString) || /[^/\]]$/.test(ipaString)) {
		console.log("User:Opencooper/sayIpa.js: IPA string of '" + ipaString + "' discarded");
		return;
	}
	
	$(this).append("<span class='sayIpa'> 〰</span>");
	$(this).children(".sayIpa").on('click', null, ipaString, sayIpa);
}

function sayIpa(event) {
	var ipaString = event.data;
	var msg = new SpeechSynthesisUtterance(ipaString);
	window.speechSynthesis.speak(msg);
}

// If we're reading an article
if ((mw.config.get('wgAction') === 'view'
      && mw.config.get('wgIsArticle')
      && !location.search.split('oldid=')[1])) { // Old revision
    $(".IPA").each(attachSpeaker);
    
    jQuery(document).on('keyup', function(e) {
    if (e.key === "Escape") {
       window.speechSynthesis.cancel();
    }
});
}