MediaWiki:Gadget-speechSynthewiki.js: различия между версиями
Перейти к навигации
Перейти к поиску
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки Метка: отменено |
||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Speech Synthewiki — гаджет озвучки статей браузером пользователя | * Speech Synthewiki — гаджет озвучки статей браузером пользователя | ||
* Версия 0. | * Версия 0.4.1 — MediaWiki 1.39.1 / 1.43; скины Vector 2022 / Vector 2010 / Monobook | ||
* Языки | * Языки интерфейса: ru / en / eo / udm (по языку пользователя) | ||
* Озвучка — русским голосом (или выбранным вручную) | |||
*/ | */ | ||
/* global mw, $ */ | /* global mw, $ */ | ||
| Строка 20: | Строка 21: | ||
speakAll: '🔊 озвучить всё', | speakAll: '🔊 озвучить всё', | ||
noText: 'Под этим заголовком нет текста для озвучки', | noText: 'Под этим заголовком нет текста для озвучки', | ||
noSynth: 'Браузер не поддерживает синтез речи' | noSynth: 'Браузер не поддерживает синтез речи', | ||
voice: 'Голос', | |||
rate: 'Скорость', | |||
pitch: 'Тон', | |||
volume: 'Громкость', | |||
reset: 'Сброс', | |||
auto: 'авто' | |||
}, | }, | ||
en: { | en: { | ||
speak: 'listen', | speak: 'listen', | ||
stop: 'stop', | stop: 'stop', | ||
speakAll: '🔊 listen to all' | speakAll: '🔊 listen to all', | ||
voice: 'Voice', | |||
rate: 'Rate', | |||
pitch: 'Pitch', | |||
volume: 'Volume', | |||
reset: 'Reset', | |||
auto: 'auto' | |||
}, | }, | ||
eo: { | eo: { | ||
speak: 'laŭtlegi', | speak: 'laŭtlegi', | ||
stop: 'halti', | stop: 'halti', | ||
speakAll: '🔊 laŭtlegi ĉion' | speakAll: '🔊 laŭtlegi ĉion', | ||
voice: 'Voĉo', | |||
rate: 'Rapido', | |||
pitch: 'Tono', | |||
volume: 'Laŭteco', | |||
reset: 'Restarigi', | |||
auto: 'aŭtomata' | |||
}, | |||
udm: { | |||
speak: 'лэсьтыны', | |||
stop: 'дугдыны', | |||
speakAll: '🔊 ванзэ лэсьтыны', | |||
voice: 'Куара', | |||
rate: 'Ӝоглык', | |||
pitch: 'Тон', | |||
volume: 'Куаралык', | |||
reset: 'Кутскон', | |||
auto: 'авто' | |||
} | } | ||
}; | }; | ||
| Строка 41: | Строка 71: | ||
var ui = (mw.config.get('wgUserLanguage') || '').toLowerCase(); | var ui = (mw.config.get('wgUserLanguage') || '').toLowerCase(); | ||
if (ui.indexOf('udm') === 0) return 'udm'; | |||
if (ui.indexOf('en') === 0) return 'en'; | if (ui.indexOf('en') === 0) return 'en'; | ||
if (ui.indexOf('eo') === 0) return 'eo'; | if (ui.indexOf('eo') === 0) return 'eo'; | ||
| Строка 84: | Строка 115: | ||
'.vector-toc', '.mw-toc', '#mw-panel-toc' | '.vector-toc', '.mw-toc', '#mw-panel-toc' | ||
].join(','); | ].join(','); | ||
// ---------- настройки ---------- | |||
var DEFAULT_SETTINGS = { | |||
voiceURI: '', | |||
rate: 1.0, | |||
pitch: 1.0, | |||
volume: 1.0 | |||
}; | |||
var settings = (function loadSettings() { | |||
try { | |||
var raw = mw.storage.get('cyclo-tts-settings'); | |||
if (raw) return $.extend({}, DEFAULT_SETTINGS, JSON.parse(raw)); | |||
} catch (e) { /* ignore */ } | |||
return $.extend({}, DEFAULT_SETTINGS); | |||
})(); | |||
function saveSettings() { | |||
try { | |||
mw.storage.set('cyclo-tts-settings', JSON.stringify(settings)); | |||
} catch (e) { /* ignore */ } | |||
} | |||
function applySettingsToUtterance(utt) { | |||
utt.rate = Number(settings.rate) || 1.0; | |||
utt.pitch = Number(settings.pitch) || 1.0; | |||
utt.volume = Number(settings.volume) || 1.0; | |||
var voices = window.speechSynthesis.getVoices() || []; | |||
if (settings.voiceURI) { | |||
var chosen = voices.find(function (v) { return v.voiceURI === settings.voiceURI; }); | |||
if (chosen) { utt.voice = chosen; return; } | |||
} | |||
var auto = getRussianVoice(); | |||
if (auto) utt.voice = auto; | |||
} | |||
// ---------- голоса ---------- | // ---------- голоса ---------- | ||
| Строка 252: | Строка 319: | ||
return chunks.join('\n'); | return chunks.join('\n'); | ||
} | |||
// ---------- панель настроек ---------- | |||
function buildSettingsPanel() { | |||
var $panel = $('<div class="cyclo-tts-settings" style="margin:.5em 0;font-size:90%;"></div>'); | |||
// --- голос --- | |||
var $voiceWrap = $('<label style="margin-right:1em;"></label>'); | |||
$voiceWrap.append($('<span class="cyclo-tts-label-voice"></span>').text(T.voice + ': ')); | |||
var $voiceSel = $('<select class="cyclo-tts-voice"></select>'); | |||
$voiceWrap.append($voiceSel); | |||
function fillVoices() { | |||
var voices = window.speechSynthesis.getVoices() || []; | |||
var langPrefix = LANG === 'ru' ? 'ru' | |||
: LANG === 'eo' ? 'eo' | |||
: LANG === 'udm' ? 'udm' | |||
: 'en'; | |||
var preferred = voices.filter(function (v) { | |||
return (v.lang || '').toLowerCase().indexOf(langPrefix) === 0; | |||
}); | |||
var others = voices.filter(function (v) { | |||
return preferred.indexOf(v) === -1; | |||
}); | |||
var list = preferred.concat(others); | |||
$voiceSel.empty(); | |||
$voiceSel.append($('<option value=""></option>').text(T.auto + ' (' + langPrefix + ')')); | |||
list.forEach(function (v) { | |||
var label = v.name + ' [' + v.lang + ']'; | |||
$voiceSel.append($('<option></option>').attr('value', v.voiceURI).text(label)); | |||
}); | |||
$voiceSel.val(settings.voiceURI || ''); | |||
} | |||
fillVoices(); | |||
window.speechSynthesis.addEventListener('voiceschanged', fillVoices); | |||
$voiceSel.on('change', function () { | |||
settings.voiceURI = $(this).val(); | |||
saveSettings(); | |||
}); | |||
// --- скорость --- | |||
var $rateWrap = $('<label style="margin-right:1em;"></label>'); | |||
$rateWrap.append($('<span class="cyclo-tts-label-rate"></span>').text(T.rate + ': ')); | |||
var $rate = $('<input type="range" min="0.5" max="2" step="0.1" class="cyclo-tts-rate">').val(settings.rate); | |||
var $rateVal = $('<span></span>').text(settings.rate); | |||
$rate.on('input', function () { | |||
settings.rate = parseFloat($(this).val()); | |||
$rateVal.text(settings.rate); | |||
saveSettings(); | |||
}); | |||
$rateWrap.append($rate).append($rateVal); | |||
// --- тон --- | |||
var $pitchWrap = $('<label style="margin-right:1em;"></label>'); | |||
$pitchWrap.append($('<span class="cyclo-tts-label-pitch"></span>').text(T.pitch + ': ')); | |||
var $pitch = $('<input type="range" min="0.5" max="2" step="0.1" class="cyclo-tts-pitch">').val(settings.pitch); | |||
var $pitchVal = $('<span></span>').text(settings.pitch); | |||
$pitch.on('input', function () { | |||
settings.pitch = parseFloat($(this).val()); | |||
$pitchVal.text(settings.pitch); | |||
saveSettings(); | |||
}); | |||
$pitchWrap.append($pitch).append($pitchVal); | |||
// --- громкость --- | |||
var $volWrap = $('<label style="margin-right:1em;"></label>'); | |||
$volWrap.append($('<span class="cyclo-tts-label-volume"></span>').text(T.volume + ': ')); | |||
var $vol = $('<input type="range" min="0" max="1" step="0.05" class="cyclo-tts-volume">').val(settings.volume); | |||
var $volVal = $('<span></span>').text(settings.volume); | |||
$vol.on('input', function () { | |||
settings.volume = parseFloat($(this).val()); | |||
$volVal.text(settings.volume); | |||
saveSettings(); | |||
}); | |||
$volWrap.append($vol).append($volVal); | |||
// --- сброс --- | |||
var $reset = $('<button type="button" class="cyclo-tts-reset"></button>').text(T.reset); | |||
$reset.on('click', function (e) { | |||
e.preventDefault(); | |||
settings = $.extend({}, DEFAULT_SETTINGS); | |||
saveSettings(); | |||
$voiceSel.val(''); | |||
$rate.val(settings.rate); $rateVal.text(settings.rate); | |||
$pitch.val(settings.pitch); $pitchVal.text(settings.pitch); | |||
$vol.val(settings.volume); $volVal.text(settings.volume); | |||
}); | |||
$panel.append($voiceWrap).append($rateWrap).append($pitchWrap).append($volWrap).append($reset); | |||
return $panel; | |||
} | } | ||
| Строка 293: | Строка 453: | ||
currentUtterance = new SpeechSynthesisUtterance(text); | currentUtterance = new SpeechSynthesisUtterance(text); | ||
currentUtterance.lang = 'ru-RU'; | currentUtterance.lang = 'ru-RU'; // озвучка всегда русским голосом | ||
ensureVoices(function () { | ensureVoices(function () { | ||
applySettingsToUtterance(currentUtterance); | |||
currentUtterance.onstart = function () { | currentUtterance.onstart = function () { | ||
| Строка 321: | Строка 477: | ||
} | } | ||
// ---------- вставка кнопок ---------- | // ---------- вставка кнопок и панели ---------- | ||
function addButtons() { | function addButtons() { | ||
var $root = $('#mw-content-text .mw-parser-output'); | var $root = $('#mw-content-text .mw-parser-output'); | ||
| Строка 327: | Строка 483: | ||
if (!$root.length) return; | if (!$root.length) return; | ||
// --- кнопка преамбулы --- | // --- кнопка преамбулы + панель настроек --- | ||
var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first(); | var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first(); | ||
var hasLead = false; | var hasLead = false; | ||
| Строка 348: | Строка 504: | ||
$leadBtn.on('click', onClick); | $leadBtn.on('click', onClick); | ||
$leadBar.append($leadBtn); | $leadBar.append($leadBtn); | ||
$leadBar.append(buildSettingsPanel()); | |||
$root.prepend($leadBar); | $root.prepend($leadBar); | ||
} else if (!hasLead && !$root.find('.cyclo-tts-settings').length) { | |||
var $leadBar2 = $('<div class="cyclo-tts-lead" style="margin:.5em 0;"></div>'); | |||
$leadBar2.append(buildSettingsPanel()); | |||
$root.prepend($leadBar2); | |||
} | } | ||
| Строка 384: | Строка 545: | ||
LANG = detectLang(); | LANG = detectLang(); | ||
T = I18N[LANG] || I18N.ru; | T = I18N[LANG] || I18N.ru; | ||
$('.cyclo-tts-start a').text(T.speak); | $('.cyclo-tts-start a').text(T.speak); | ||
$('.cyclo-tts-lead a').text(T.speakAll); | $('.cyclo-tts-lead a').text(T.speakAll); | ||
var $panel = $('.cyclo-tts-settings'); | |||
if ($panel.length) { | |||
$panel.find('.cyclo-tts-label-voice').text(T.voice + ': '); | |||
$panel.find('.cyclo-tts-label-rate').text(T.rate + ': '); | |||
$panel.find('.cyclo-tts-label-pitch').text(T.pitch + ': '); | |||
$panel.find('.cyclo-tts-label-volume').text(T.volume + ': '); | |||
$panel.find('.cyclo-tts-reset').text(T.reset); | |||
var langPrefix = LANG === 'ru' ? 'ru' | |||
: LANG === 'eo' ? 'eo' | |||
: LANG === 'udm' ? 'udm' | |||
: 'en'; | |||
$panel.find('.cyclo-tts-voice option[value=""]').text(T.auto + ' (' + langPrefix + ')'); | |||
} | |||
}); | }); | ||
}); | }); | ||
}); | }); | ||
})(); | })(); | ||
Версия от 21:30, 3 ноября 2026
/**
* Speech Synthewiki — гаджет озвучки статей браузером пользователя
* Версия 0.4.1 — MediaWiki 1.39.1 / 1.43; скины Vector 2022 / Vector 2010 / Monobook
* Языки интерфейса: ru / en / eo / udm (по языку пользователя)
* Озвучка — русским голосом (или выбранным вручную)
*/
/* global mw, $ */
(function () {
'use strict';
var currentUtterance = null;
var currentButton = null;
var voicesReady = false;
// ---------- локализация ----------
var I18N = {
ru: {
speak: 'озвучить',
stop: 'стоп',
speakAll: '🔊 озвучить всё',
noText: 'Под этим заголовком нет текста для озвучки',
noSynth: 'Браузер не поддерживает синтез речи',
voice: 'Голос',
rate: 'Скорость',
pitch: 'Тон',
volume: 'Громкость',
reset: 'Сброс',
auto: 'авто'
},
en: {
speak: 'listen',
stop: 'stop',
speakAll: '🔊 listen to all',
voice: 'Voice',
rate: 'Rate',
pitch: 'Pitch',
volume: 'Volume',
reset: 'Reset',
auto: 'auto'
},
eo: {
speak: 'laŭtlegi',
stop: 'halti',
speakAll: '🔊 laŭtlegi ĉion',
voice: 'Voĉo',
rate: 'Rapido',
pitch: 'Tono',
volume: 'Laŭteco',
reset: 'Restarigi',
auto: 'aŭtomata'
},
udm: {
speak: 'лэсьтыны',
stop: 'дугдыны',
speakAll: '🔊 ванзэ лэсьтыны',
voice: 'Куара',
rate: 'Ӝоглык',
pitch: 'Тон',
volume: 'Куаралык',
reset: 'Кутскон',
auto: 'авто'
}
};
function detectLang() {
try {
var explicit = mw.user.options.get('gadget-SpeechSynthewiki-lang');
if (explicit && I18N[explicit]) return explicit;
} catch (e) { /* ignore */ }
var ui = (mw.config.get('wgUserLanguage') || '').toLowerCase();
if (ui.indexOf('udm') === 0) return 'udm';
if (ui.indexOf('en') === 0) return 'en';
if (ui.indexOf('eo') === 0) return 'eo';
if (ui.indexOf('ru') === 0) return 'ru';
var content = (mw.config.get('wgContentLanguage') || '').toLowerCase();
if (I18N[content]) return content;
return 'ru';
}
var LANG = detectLang();
var T = I18N[LANG] || I18N.ru;
// fallback на русские служебные сообщения
function msg(key) {
return (T && T[key]) || I18N.ru[key] || '';
}
// ---------- служебные элементы, которые не озвучиваем ----------
var SKIP_SELECTORS = [
'#siteSub', '#contentSub', '#jump-to-nav', '.mw-jump-link',
'.mw-indicators', '.catlinks', '.printfooter', '.mw-hidden-catlinks',
'.noprint', '.metadata',
'.navbox', '.vertical-navbox', '.sistersitebox', '.ambox',
'.mbox-text-span', '.mw-references-wrap', 'ol.references',
'.reference', 'sup.reference', '.reflist',
'style', 'script',
'.mw-empty-elt', '.mw-kartographer-maplink',
'.cyclo-tts-start', '.cyclo-tts-lead',
'.mw-editsection', '.editsection',
'#toc', '.toc', '.mw-toc', '#mw-toc', '#mw-toc-heading',
'#toctitle', '.toctitle', '.vector-toc', '.vector-toc-heading',
'#mw-panel-toc', '.tocnumber', '.toctext',
'.sidebar-toc', '.minerva-toc'
].join(',');
var SKIP_TOP = [
'h1.firstHeading', '#siteSub', '#contentSub', '.mw-indicators',
'.mw-jump-link', '.printfooter', '.catlinks',
'.cyclo-tts-lead', '.cyclo-tts-start',
'#toc', '.toc', '#toctitle', '.toctitle',
'.vector-toc', '.mw-toc', '#mw-panel-toc'
].join(',');
// ---------- настройки ----------
var DEFAULT_SETTINGS = {
voiceURI: '',
rate: 1.0,
pitch: 1.0,
volume: 1.0
};
var settings = (function loadSettings() {
try {
var raw = mw.storage.get('cyclo-tts-settings');
if (raw) return $.extend({}, DEFAULT_SETTINGS, JSON.parse(raw));
} catch (e) { /* ignore */ }
return $.extend({}, DEFAULT_SETTINGS);
})();
function saveSettings() {
try {
mw.storage.set('cyclo-tts-settings', JSON.stringify(settings));
} catch (e) { /* ignore */ }
}
function applySettingsToUtterance(utt) {
utt.rate = Number(settings.rate) || 1.0;
utt.pitch = Number(settings.pitch) || 1.0;
utt.volume = Number(settings.volume) || 1.0;
var voices = window.speechSynthesis.getVoices() || [];
if (settings.voiceURI) {
var chosen = voices.find(function (v) { return v.voiceURI === settings.voiceURI; });
if (chosen) { utt.voice = chosen; return; }
}
var auto = getRussianVoice();
if (auto) utt.voice = auto;
}
// ---------- голоса ----------
function getRussianVoice() {
var voices = window.speechSynthesis.getVoices() || [];
return voices.find(function (v) {
return /^ru/i.test(v.lang) || /рус/i.test(v.name);
}) || null;
}
function ensureVoices(cb) {
if (voicesReady) { cb(); return; }
var v = window.speechSynthesis.getVoices();
if (v && v.length) { voicesReady = true; cb(); return; }
var handler = function () {
voicesReady = true;
window.speechSynthesis.removeEventListener('voiceschanged', handler);
cb();
};
window.speechSynthesis.addEventListener('voiceschanged', handler);
}
// ---------- очистка клона ----------
function cleanClone(cloned) {
cloned.find([
'.thumb', '.thumbinner', '.thumbcaption', '.magnify',
'.floatnone', '.floatleft', '.floatright',
'ul.gallery', 'div.gallery', 'li.gallerybox', 'div.thumb',
'.gallerycaption', 'sup.reference', '.metadata', '.noprint',
'img', 'a.image', 'style', 'script'
].join(',')).remove();
cloned.contents().each(function () {
if (this.nodeType === 3) {
if (/(Файл|File|Image|Изображение|Медиа):/i.test(this.nodeValue)) {
this.nodeValue = '';
}
} else if (this.nodeType === 1) {
var $el = $(this);
var href = $el.attr('href') || '';
if ($el.is('a') && /\.(jpg|jpeg|png|gif|bmp|svg|webp|ogg|mp3|wav|pdf|djvu)(\?|$)/i.test(href)) {
$el.remove();
} else if ($el.hasClass('image') || $el.hasClass('internal') || href.indexOf('Файл:') !== -1) {
$el.remove();
}
}
});
return cloned;
}
// ---------- MathML → речь ----------
function mathToSpeech($math) {
var $clone = $math.clone();
$clone.find('annotation').remove();
var parts = [];
$clone.find('msqrt').each(function () {
parts.push(' корень из ' + $(this).text().trim() + ' ');
$(this).remove();
});
$clone.find('mfrac').each(function () {
var $ch = $(this).children();
parts.push(' дробь ' + $ch.eq(0).text().trim() + ' на ' + $ch.eq(1).text().trim() + ' ');
$(this).remove();
});
$clone.find('msup').each(function () {
var $ch = $(this).children();
var base = $ch.eq(0).text().trim();
var exp = $ch.eq(1).text().trim();
if (exp === '2') parts.push(base + ' в квадрате ');
else if (exp === '3') parts.push(base + ' в кубе ');
else parts.push(base + ' в степени ' + exp + ' ');
$(this).remove();
});
$clone.find('msub').each(function () {
var $ch = $(this).children();
parts.push($ch.eq(0).text().trim() + ' с индексом ' + $ch.eq(1).text().trim() + ' ');
$(this).remove();
});
var rest = $clone.text().trim()
.replace(/×/g, ' умножить ')
.replace(/÷/g, ' разделить ')
.replace(/≠/g, ' не равно ')
.replace(/≈/g, ' приблизительно равно ')
.replace(/≤/g, ' меньше или равно ')
.replace(/≥/g, ' больше или равно ')
.replace(/±/g, ' плюс минус ')
.replace(/∞/g, ' бесконечность ')
.replace(/√/g, ' корень из ')
.replace(/π/g, ' пи ')
.replace(/∑/g, ' сумма ')
.replace(/∏/g, ' произведение ')
.replace(/∫/g, ' интеграл ')
.replace(/∂/g, ' частная производная ')
.replace(/∇/g, ' набла ')
.replace(/∈/g, ' принадлежит ')
.replace(/∉/g, ' не принадлежит ')
.replace(/∩/g, ' пересечение ')
.replace(/∪/g, ' объединение ')
.replace(/⊂/g, ' подмножество ')
.replace(/⊃/g, ' надмножество ');
if (rest) parts.push(rest);
return parts.join(' ').trim();
}
// ---------- сбор текста секции ----------
function buildSpeechText($startNode, $stopNode) {
var chunks = [];
var $node = $startNode;
while ($node.length) {
if ($stopNode && $node[0] === $stopNode[0]) break;
if (!$stopNode && $node.is('h1, h2, h3, h4, h5, h6') && $node[0] !== $startNode[0]) break;
if (!$stopNode && $node.is('.mw-heading')) break;
var $cloned = cleanClone($node.clone());
$cloned.find(SKIP_SELECTORS).remove();
if ($cloned.is(SKIP_SELECTORS)) {
$node = $node.next();
continue;
}
$cloned.find('math').each(function () {
var spoken = mathToSpeech($(this));
if (spoken) $(this).replaceWith(document.createTextNode(' формула: ' + spoken + ' '));
else $(this).remove();
});
var t = $cloned.text().replace(/\s+/g, ' ').trim();
if (t) chunks.push(t);
$node = $node.next();
}
return chunks.join('\n');
}
// ---------- сбор текста преамбулы ----------
function buildLeadText() {
var $root = $('#mw-content-text .mw-parser-output');
if (!$root.length) $root = $('#mw-content-text');
if (!$root.length) return '';
var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first();
var stopEl = $firstHeader.length ? $firstHeader[0] : null;
var chunks = [];
$root.children().each(function () {
if (stopEl && this === stopEl) return false;
var $el = $(this);
if ($el.is(SKIP_TOP)) return true;
if ($el.find('#toctitle, .toctitle').length) return true;
var $cloned = cleanClone($el.clone());
$cloned.find(SKIP_SELECTORS).remove();
if ($cloned.is(SKIP_SELECTORS)) return true;
$cloned.find('math').each(function () {
var spoken = mathToSpeech($(this));
if (spoken) $(this).replaceWith(document.createTextNode(' формула: ' + spoken + ' '));
else $(this).remove();
});
var t = $cloned.text().replace(/\s+/g, ' ').trim();
if (t) chunks.push(t);
return true;
});
return chunks.join('\n');
}
// ---------- панель настроек ----------
function buildSettingsPanel() {
var $panel = $('<div class="cyclo-tts-settings" style="margin:.5em 0;font-size:90%;"></div>');
// --- голос ---
var $voiceWrap = $('<label style="margin-right:1em;"></label>');
$voiceWrap.append($('<span class="cyclo-tts-label-voice"></span>').text(T.voice + ': '));
var $voiceSel = $('<select class="cyclo-tts-voice"></select>');
$voiceWrap.append($voiceSel);
function fillVoices() {
var voices = window.speechSynthesis.getVoices() || [];
var langPrefix = LANG === 'ru' ? 'ru'
: LANG === 'eo' ? 'eo'
: LANG === 'udm' ? 'udm'
: 'en';
var preferred = voices.filter(function (v) {
return (v.lang || '').toLowerCase().indexOf(langPrefix) === 0;
});
var others = voices.filter(function (v) {
return preferred.indexOf(v) === -1;
});
var list = preferred.concat(others);
$voiceSel.empty();
$voiceSel.append($('<option value=""></option>').text(T.auto + ' (' + langPrefix + ')'));
list.forEach(function (v) {
var label = v.name + ' [' + v.lang + ']';
$voiceSel.append($('<option></option>').attr('value', v.voiceURI).text(label));
});
$voiceSel.val(settings.voiceURI || '');
}
fillVoices();
window.speechSynthesis.addEventListener('voiceschanged', fillVoices);
$voiceSel.on('change', function () {
settings.voiceURI = $(this).val();
saveSettings();
});
// --- скорость ---
var $rateWrap = $('<label style="margin-right:1em;"></label>');
$rateWrap.append($('<span class="cyclo-tts-label-rate"></span>').text(T.rate + ': '));
var $rate = $('<input type="range" min="0.5" max="2" step="0.1" class="cyclo-tts-rate">').val(settings.rate);
var $rateVal = $('<span></span>').text(settings.rate);
$rate.on('input', function () {
settings.rate = parseFloat($(this).val());
$rateVal.text(settings.rate);
saveSettings();
});
$rateWrap.append($rate).append($rateVal);
// --- тон ---
var $pitchWrap = $('<label style="margin-right:1em;"></label>');
$pitchWrap.append($('<span class="cyclo-tts-label-pitch"></span>').text(T.pitch + ': '));
var $pitch = $('<input type="range" min="0.5" max="2" step="0.1" class="cyclo-tts-pitch">').val(settings.pitch);
var $pitchVal = $('<span></span>').text(settings.pitch);
$pitch.on('input', function () {
settings.pitch = parseFloat($(this).val());
$pitchVal.text(settings.pitch);
saveSettings();
});
$pitchWrap.append($pitch).append($pitchVal);
// --- громкость ---
var $volWrap = $('<label style="margin-right:1em;"></label>');
$volWrap.append($('<span class="cyclo-tts-label-volume"></span>').text(T.volume + ': '));
var $vol = $('<input type="range" min="0" max="1" step="0.05" class="cyclo-tts-volume">').val(settings.volume);
var $volVal = $('<span></span>').text(settings.volume);
$vol.on('input', function () {
settings.volume = parseFloat($(this).val());
$volVal.text(settings.volume);
saveSettings();
});
$volWrap.append($vol).append($volVal);
// --- сброс ---
var $reset = $('<button type="button" class="cyclo-tts-reset"></button>').text(T.reset);
$reset.on('click', function (e) {
e.preventDefault();
settings = $.extend({}, DEFAULT_SETTINGS);
saveSettings();
$voiceSel.val('');
$rate.val(settings.rate); $rateVal.text(settings.rate);
$pitch.val(settings.pitch); $pitchVal.text(settings.pitch);
$vol.val(settings.volume); $volVal.text(settings.volume);
});
$panel.append($voiceWrap).append($rateWrap).append($pitchWrap).append($volWrap).append($reset);
return $panel;
}
// ---------- клик ----------
function onClick(event) {
event.preventDefault();
var a = event.currentTarget;
if (currentButton === a && window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
$(a).text(T.speak);
currentButton = null;
currentUtterance = null;
return;
}
var text;
if ($(a).data('lead')) {
text = buildLeadText();
} else {
var $heading = $(a).closest('.mw-heading, h1, h2, h3, h4, h5, h6');
var $realHeader = $heading.is('.mw-heading')
? $heading.children('h1,h2,h3,h4,h5,h6')
: $heading;
var $start = $realHeader.next();
if (!$start.length) $start = $realHeader.parent().next();
var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first();
text = $start.length ? buildSpeechText($start, $stop.length ? $stop : null) : '';
}
if (!text) {
mw.notify(msg('noText'), { type: 'warn' });
return;
}
if (window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
if (currentButton) $(currentButton).text(T.speak);
}
currentUtterance = new SpeechSynthesisUtterance(text);
currentUtterance.lang = 'ru-RU'; // озвучка всегда русским голосом
ensureVoices(function () {
applySettingsToUtterance(currentUtterance);
currentUtterance.onstart = function () {
$(a).text(T.stop);
currentButton = a;
};
currentUtterance.onend = function () {
$(a).text(T.speak);
if (currentButton === a) { currentButton = null; currentUtterance = null; }
};
currentUtterance.onerror = function (ev) {
if (ev.error !== 'interrupted' && ev.error !== 'canceled') {
$(a).text(T.speak);
if (currentButton === a) { currentButton = null; currentUtterance = null; }
}
};
window.speechSynthesis.speak(currentUtterance);
});
}
// ---------- вставка кнопок и панели ----------
function addButtons() {
var $root = $('#mw-content-text .mw-parser-output');
if (!$root.length) $root = $('#mw-content-text');
if (!$root.length) return;
// --- кнопка преамбулы + панель настроек ---
var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first();
var hasLead = false;
$root.children().each(function () {
if ($firstHeader.length && this === $firstHeader[0]) return false;
var $el = $(this);
if ($el.is('.cyclo-tts-lead, .cyclo-tts-start, #toc, .toc, .vector-toc, .mw-toc, #mw-panel-toc')) return true;
if ($el.is('p, ul, ol, dl, table, blockquote') && $el.text().trim()) {
hasLead = true;
return false;
}
return true;
});
if (hasLead && !$root.find('.cyclo-tts-lead').length) {
var $leadBar = $('<div class="cyclo-tts-lead" style="margin:.5em 0;"></div>');
var $leadBtn = $('<a href="#" style="cursor:pointer;"></a>')
.text(T.speakAll)
.data('lead', true);
$leadBtn.on('click', onClick);
$leadBar.append($leadBtn);
$leadBar.append(buildSettingsPanel());
$root.prepend($leadBar);
} else if (!hasLead && !$root.find('.cyclo-tts-settings').length) {
var $leadBar2 = $('<div class="cyclo-tts-lead" style="margin:.5em 0;"></div>');
$leadBar2.append(buildSettingsPanel());
$root.prepend($leadBar2);
}
// --- кнопки у заголовков ---
$root.find('.mw-heading, h1, h2, h3, h4, h5, h6').each(function () {
var $h = $(this);
if ($h.hasClass('cyclo-tts-start')) return;
if ($h.is('#mw-toc-heading, #toctitle, .toctitle')) return;
if ($h.closest('#toc, .toc, .vector-toc, .mw-toc, #mw-panel-toc').length) return;
if ($h.find('#toctitle, .toctitle').length) return;
var $edit = $h.find('.mw-editsection, .editsection').first();
if (!$edit.length) return;
if ($edit.prev().hasClass('cyclo-tts-start')) return;
var $span = $('<span class="mw-editsection cyclo-tts-start">[<a href="#" style="cursor:pointer;"></a>]</span> ');
$span.find('a').text(T.speak);
$span.on('click', 'a', onClick);
$edit.before($span);
});
}
// ---------- запуск ----------
mw.loader.using(['jquery'], function () {
$(function () {
if (!window.speechSynthesis) {
console.warn('[Speech Synthewiki] ' + msg('noSynth'));
return;
}
addButtons();
// смена языка интерфейса на лету
mw.hook('userjs.languageChanged').add(function () {
LANG = detectLang();
T = I18N[LANG] || I18N.ru;
$('.cyclo-tts-start a').text(T.speak);
$('.cyclo-tts-lead a').text(T.speakAll);
var $panel = $('.cyclo-tts-settings');
if ($panel.length) {
$panel.find('.cyclo-tts-label-voice').text(T.voice + ': ');
$panel.find('.cyclo-tts-label-rate').text(T.rate + ': ');
$panel.find('.cyclo-tts-label-pitch').text(T.pitch + ': ');
$panel.find('.cyclo-tts-label-volume').text(T.volume + ': ');
$panel.find('.cyclo-tts-reset').text(T.reset);
var langPrefix = LANG === 'ru' ? 'ru'
: LANG === 'eo' ? 'eo'
: LANG === 'udm' ? 'udm'
: 'en';
$panel.find('.cyclo-tts-voice option[value=""]').text(T.auto + ' (' + langPrefix + ')');
}
});
});
});
})();