使用 JavaScript 实现文本转语音转换器
🗣️
实时语音分析
使用 SpeechSynthesis API 可以将 HTML、CSS 和 JavaScript 中的文本转换为语音。
SpeechSynthesis API是一个内置的 JavaScript API,它允许您直接在浏览器中将文本转换为语音,而无需任何外部库。
以下示例展示了如何使用 SpeechSynthesis API在 HTML、CSS 和 JavaScript中将文本转换为语音:
HTML 代码
<div id="text-to-speech">
<textarea id="text"></textarea>
<button id="speak-button">Speak</button>
</div>
CSS 代码
#text-to-speech {
display: flex;
flex-direction: column;
align-items: center;
}
#text {
width: 300px;
height: 100px;
padding: 10px;
margin-bottom: 10px;
}
#speak-button {
padding: 10px;
font-size: 18px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
JavaScript 代码
// Get the text area and speak button elements
let textArea = document.getElementById("text");
let speakButton = document.getElementById("speak-button");
// Add an event listener to the speak button
speakButton.addEventListener("click", function() {
// Get the text from the text area
let text = textArea.value;
// Create a new SpeechSynthesisUtterance object
let utterance = new SpeechSynthesisUtterance();
// Set the text and voice of the utterance
utterance.text = text;
utterance.voice = window.speechSynthesis.getVoices()[0];
// Speak the utterance
window.speechSynthesis.speak(utterance);
});
此示例在 HTML 中创建了一个文本区域和一个按钮,使用 CSS 设置它们的样式,然后使用 JavaScript 向按钮添加一个事件监听器,当单击按钮时,将文本区域中的文本转换为语音。
相关帖子:
- 响应式页脚 HTML CSS
- 海德拉巴的IB学校
- 使用 JavaScript 的简单秒表
- 怀特菲尔德的幼儿园
- JavaScript 密码生成器
- 海德拉巴最好的国际学校
- 使用 HTML 和 CSS 的侧边栏菜单
这只是一个基本示例,您可以根据需要进一步自定义,例如,为语音合成添加更多选项,您还可以使用 responsivevoice.js、meSpeak.js 或 annyang.js 等库来添加更多功能和特性。
文章来源:https://dev.to/shantanu_jana/text-to-speech-converter-with-javascript-30oo