Web Speech API 文本转语音:如何使用一个 JavaScript 代码来读取多个文本?

是否可以使用单个 JavaScript 代码(借助 PHP 或其他内容)来读取所有不同的文本,而不是像我当前的代码那样为每个要读取的文本使用一个代码?在此示例中,只有 4 篇文本需要阅读,但我的一个网页包含大约 130 篇文本。


以下是 4 个 PHP 不同页面中的 HTML 代码(我使用 include php 在需要的地方添加这些按钮):


<div class="read"><button id="lectureObjectif">Écoutez</button>&nbsp<button id="pauseObjectif">Pause</button>&nbsp<button id="reprendreObjectif">Reprendre</button>&nbsp<button id="arretObjectif">Arrêtter</button></div>


<div class="read"><button id="lecturePourquoi">Écoutez</button>&nbsp<button id="pausePourquoi">Pause</button>&nbsp<button id="reprendrePourquoi">Reprendre</button>&nbsp<button id="arretPourquoi">Arrêtter</button></div>


<div class="read"><button id="lectureNouvelles">Écoutez</button>&nbsp<button id="pauseNouvelles">Pause</button>&nbsp<button id="reprendreNouvelles">Reprendre</button>&nbsp<button id="arretNouvelles">Arrêtter</button></div>


<div class="read"><button id="lectureDissonance">Écoutez</button>&nbsp<button id="pauseDissonance">Pause</button>&nbsp<button id="reprendreDissonance">Reprendre</button>&nbsp<button id="arretDissonance">Arrêtter</button></div>

这是一页上的 JavasCript 代码(我不想使用第三方 JavaScript)。我是编程新手,对于 JavaScript 也很新手。


慕标琳琳
浏览 127回答 3
3回答

慕雪6442864

我终于成功让它工作了(除了我的手机浏览器)。我不得不替换这段代码:&nbsp; &nbsp; function make_events($textname) {&nbsp; &nbsp; $clicks = [];&nbsp; &nbsp; $clicks[] = "document.getElementById('lecture{$textname}').onclick = doLecture('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('pause{$textname}').onclick = doPause('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('reprendre{$textname}').onclick = doReprendre('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('arret{$textname}').onclick = doArret('{$textname}');";&nbsp; &nbsp; return implode("\n", $clicks);}&nbsp;通过这段代码:function make_events( $textname ) {&nbsp; &nbsp; $clicks = [];&nbsp; &nbsp; $clicks[] = "document.getElementById('lecture{$textname}').onclick = function(){doLecture('{$textname}');};";&nbsp; &nbsp; $clicks[] = "document.getElementById('pause{$textname}').onclick = function(){doPause('{$textname}');};";&nbsp; &nbsp; $clicks[] = "document.getElementById('reprendre{$textname}').onclick = function(){doReprendre('{$textname}');};";&nbsp; &nbsp; $clicks[] = "document.getElementById('arret{$textname}').onclick = function(){doArret('{$textname}');};";&nbsp; &nbsp; return implode( "\n", $clicks );}再次感谢 Markus AO 的帮助。但是,同样,这在我的手机浏览器中不起作用(或无法正常工作)。例如,在某些浏览器中,我可以说出第一个文本,然后停止它,但其他文本不可播放。对于所有浏览器,暂停和恢复根本不起作用。

12345678_0001

我现在的处境是:事情已经开始成形,但阅读却没有发生。在本练习中,我仅使用一个 PHP 文件:<body><?php&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; //&nbsp; "id"s&nbsp; of the "div"s to be spoken$texts = ['Objectif', 'Pourquoi'];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;$buttons = [];$events = [];foreach($texts as $text) {&nbsp; &nbsp; $buttons[$text] = make_buttons($text);&nbsp; &nbsp; $events[$text] = make_events($text);}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function make_buttons($textname) {&nbsp; &nbsp; $buttons = [];&nbsp; &nbsp; $buttons[] = '<button id="lecture' . $textname . '">Écouter</button>';&nbsp; &nbsp; $buttons[] = '<button id="pause' . $textname . '">Pause</button>';&nbsp; &nbsp; $buttons[] = '<button id="reprendre' . $textname . '">Reprendre</button>';&nbsp; &nbsp; $buttons[] = '<button id="arret' . $textname . '">Arrêtter</button>';&nbsp; &nbsp; return implode("&nbsp;", $buttons);&nbsp; &nbsp;&nbsp;}&nbsp; &nbsp; function make_events($textname) {&nbsp; &nbsp; $clicks = [];&nbsp; &nbsp; $clicks[] = "document.getElementById('lecture{$textname}').onclick = doLecture('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('pause{$textname}').onclick = doPause('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('reprendre{$textname}').onclick = doReprendre('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('arret{$textname}').onclick = doArret('{$textname}');";&nbsp; &nbsp; return implode("\n", $clicks);}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ?>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <?php&nbsp; &nbsp;// Show buttons for the div with the id Objectif to be spoken&nbsp; &nbsp; echo "<div>{$buttons['Objectif']}</div>";?>&nbsp; &nbsp; <!-- The div (with the Objectif id) to be spoken -->&nbsp; &nbsp; <div id="Objectif" class="moi-wrap-text">&nbsp; &nbsp; &nbsp; &nbsp; <p>L'objectif de ce site est important. </p>&nbsp; &nbsp; </div>&nbsp; &nbsp; <?php&nbsp; &nbsp;// Show buttons for the div with the id Pourquoi to be spoken&nbsp; &nbsp; echo "<div>{$buttons['Pourquoi']}</div>";?>&nbsp; &nbsp; <!-- The div (with the Pourquoi id) to be spoken -->&nbsp; &nbsp; <div id="Pourquoi" class="moi-wrap-text">&nbsp; &nbsp; &nbsp; &nbsp; <p>Pourquoi est-il important de savoir?</p>&nbsp; &nbsp; </div>&nbsp; &nbsp; <!-- External JavaScript file -->&nbsp; &nbsp; <script src="scrypte.js" defer></script></body>这是我的 JavaScript 文件// Function for Speakfunction doLecture(textName) {&nbsp; &nbsp; /* Removes all utterances from the utterance queue and&nbsp; &nbsp; if an utterance is currently being spoken, speaking will stop */&nbsp; &nbsp; speechSynthesis.cancel();&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; parole.lang = 'fr-Fr'; // language, default is 'en-US'&nbsp; &nbsp; parole.pitch = 1; // 0 à 2 = hauteur&nbsp; &nbsp; parole.rate = 1.3; // 0.1 à 10 = vitesse&nbsp; &nbsp; parole.volume = 1; // 0 à 1 = volume&nbsp; &nbsp; // Get the DOM object&nbsp; &nbsp; parole.text = document.getElementById(textName).textContent;&nbsp; &nbsp; // Speak&nbsp; &nbsp; speechSynthesis.speak(parole);}// Function for Pausefunction doPause(textName) {&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; // Get the DOM object&nbsp; &nbsp; parole.text = document.getElementById(textName).textContent;&nbsp; &nbsp; // Pause speaking&nbsp; &nbsp; speechSynthesis.pause(parole);}// Function for Resumefunction doReprendre(textName) {&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; // Get the DOM object&nbsp; &nbsp; parole.text = document.getElementById(textName).textContent;&nbsp; &nbsp; // Resume speaking&nbsp; &nbsp; speechSynthesis.resume(parole);}// Function for Stopfunction doArret(textName) {&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; // Get the DOM object&nbsp; &nbsp; parole.text = document.getElementById(textName).textContent;&nbsp; &nbsp; // Stop speaking&nbsp; &nbsp; speechSynthesis.stop(parole);}$events = implode("\n", $events);

白板的微信

是的,这是可能的:通过认真重构你的显式代码。基本上,你需要抽象,即。根据您确定的常见模式生成变体。我不会为您编写所有代码,但是这里有一个带有大量示例的演练。首先,我们把代码拆开;仅查看许多重复中的一个。下面,我们对单个文本的必要代码进行采样,并将文本名称替换为占位符,{{ TEXTNAME }}以帮助您查看所有重复的内容。对于每个文本,您都有 HTML 按钮,如下所示:<button id="lecture{{ TEXTNAME }}">Écoutez</button><button id="pause{{ TEXTNAME }}">Pause</button><button id="reprendre{{ TEXTNAME }}">Reprendre</button><button id="arret{{ TEXTNAME }}">Arrêtter</button>然后,您将获得如下 JavaScript。/* You don't really need the following five "let"s.&nbsp;&nbsp; &nbsp;Get the relevant DOM objects inside the functions. */let btnLecturet{{ TEXTNAME }} = document.getElementById("lecture{{ TEXTNAME }}");let btnPause{{ TEXTNAME }} = document.getElementById("pause{{ TEXTNAME }}");let btnReprendre{{ TEXTNAME }} = document.getElementById("reprendre{{ TEXTNAME }}");let btnArret{{ TEXTNAME }} = document.getElementById("arret{{ TEXTNAME }}");let div{{ TEXTNAME }} = document.getElementById("{{ TEXTNAME }}");/* Here we have four *explicit* functions that are&nbsp;&nbsp; &nbsp;unnecessarily repeated for each event handler definition: */btnArret{{ TEXTNAME }}.onclick = function () {&nbsp; &nbsp; speechSynthesis.cancel();}btnLecture{{ TEXTNAME }}.onclick = function () {&nbsp; &nbsp; speechSynthesis.cancel();&nbsp; &nbsp; /*let texte = "Coucou";*/&nbsp; &nbsp; let texte{{ TEXTNAME }} = div{{ TEXTNAME }}.textContent;&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; parole.lang = 'fr-Fr'; // language, default is 'en-US'&nbsp; &nbsp; parole.text = texte{{ TEXTNAME }};&nbsp; &nbsp; parole.pitch = 1; // 0 à 2 = hauteur&nbsp; &nbsp; parole.rate = 1.3; // 0.1 à 10 = vitesse&nbsp; &nbsp; parole.volume = 1; // 0 à 1 = volume&nbsp; &nbsp; // fair parler&nbsp; &nbsp; speechSynthesis.speak(parole);}btnPause{{ TEXTNAME }}.onclick = function () {&nbsp; &nbsp; let texte{{ TEXTNAME }} = div{{ TEXTNAME }}.textContent;&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; parole.text = texte{{ TEXTNAME }};&nbsp; &nbsp; // fair une pause&nbsp; &nbsp; speechSynthesis.pause(parole);}btnReprendre{{ TEXTNAME }}.onclick = function () {&nbsp; &nbsp; let texte{{ TEXTNAME }} = div{{ TEXTNAME }}.textContent;&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; parole.text = texte{{ TEXTNAME }};&nbsp; &nbsp; // reprendre la lecture&nbsp; &nbsp; speechSynthesis.resume(parole);}您会注意到上面的 Javascript 函数包含不必要的显式信息(“TEXTNAME”)。这使得它们不可重复使用。如果您只有一两个固定的实现,那么这样做就可以了;但你有很多东西,并且你想轻松更新。现在,函数的一个很酷的事情是:它们可以接受限定其操作或返回值的参数,从而允许您针对任意数量的变体情况重复使用相同的代码。假设您执行了以下操作(例如,您将对其余函数执行类似的“概括”):function doPause(textName) {&nbsp; &nbsp; // instancier un objet d'énonciation&nbsp; &nbsp; let parole = new SpeechSynthesisUtterance();&nbsp; &nbsp; /* simply get the DOM object right here: */&nbsp; &nbsp; parole.text = document.getElementById(textName).textContent;&nbsp; &nbsp; // fair une pause&nbsp; &nbsp; speechSynthesis.pause(parole);}然后,我们有一个通用的暂停动作函数,它将文本的名称/标识符作为参数,它可以应用于任意数量的情况(下面的示例遵循您的旧代码):btnPauseWHATEVERTEXT.onclick = doPause("WHATEVERTEXT");btnPauseQUESTCEQUECEST.onclick = doPause("QUESTCEQUECEST");这已经更容易管理了,对吧?您只需要声明一组函数:doArret(textName)、doLecture(textName)、doPause(textName)和doReprendre(textName)。然后,剩下的就是拼出按钮和事件处理程序。现在,切换到 PHP。假设您有以下函数:function make_buttons($textname) {&nbsp; &nbsp; $buttons = [];&nbsp; &nbsp; $buttons[] = '<button id="lecture' . $textname . '">Écoutez</button>';&nbsp; &nbsp; $buttons[] = '<button id="pause' . $textname . '">Pause</button>';&nbsp; &nbsp; $buttons[] = '<button id="reprendre' . $textname . '">Écoutez</button>';&nbsp; &nbsp; $buttons[] = '<button id="arret' . $textname . '">Arrêtter</button>';&nbsp; &nbsp; return implode("&nbsp;", $buttons);}你的小“纽扣工厂”就在那里。然后你可以有另一个通用函数来处理按钮事件处理程序集:function make_events($textname) {&nbsp; &nbsp; $clicks = [];&nbsp; &nbsp; $clicks[] = "document.getElementById('lecture{$textname}').onclick = doLecture('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('pause{$textname}').onclick = doPause('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('reprendre{$textname}').onclick = doReprendre('{$textname}');";&nbsp; &nbsp; $clicks[] = "document.getElementById('arret{$textname}').onclick = doArret('{$textname}');";&nbsp; &nbsp; return implode("\n", $clicks);}这将为您提供用于为给定文本创建点击的 JS 代码。现在,您需要做的就是将它们放在一起,如下所示(同样使用 PHP):$texts = ['Objectif', 'Subjectif', 'Reflectif', 'Asterix', 'Obelix'];$buttons = [];$events = [];foreach($texts as $text) {&nbsp; &nbsp; $buttons[$text] = make_buttons($text);&nbsp; &nbsp; $events[$text] = make_events($text);}// If you want to flatten the $buttons array into a string,// do this; and put $buttons to wherever all the buttons go$buttons = implode("\n", $buttons);&nbsp;// or otherwise, you can get a particular text's buttons like this:echo "<div>Voici les buttons pour text Reflectif: {$buttons['Reflectif']}</div>";// and put the events where your JS is, after the generic "doStuff()" functions$events = implode("\n", $events);通过上述措施,您可以避免很多不必要的重复。让我们回顾一下:将显式 JS 函数清理为可以分配给 onclick-events 的通用函数(带参数);创建生成按钮和事件处理程序的 PHP 函数。使用这些函数循环遍历给定页面的文本名称;并将 HTML 和 JS 放在它们所属的位置。花更多时间思考和学习如何抽象和重用代码。当然还有其他方法可以处理这个问题。例如,您可以仅在客户端使用 JS 生成更多内容。由于您刚刚开始编程,因此这更像是一个简单且具有教育意义的重构;圆滑和优化并不是最终的定论;但它应该会让你的生活变得更加轻松。快乐的作业,让我们知道你的代码是如何演变的!=(^o^)=
打开App,查看更多内容
随时随地看视频慕课网APP