User:Opencooper/sayIpa.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | Documentation for this user script can be added at User:Opencooper/sayIpa. |
// Superseded by: https://en.wikipedia.org/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();
}
});
}