查看: 207|回复: 0

[JS代码] 文字转语音简单方案(Google浏览器下亲测有效)

[复制链接]
xuanxiao 发表于 2023-11-20 16:55:51 | 显示全部楼层 |阅读模式
支持脱机/局域网环境,无需外部API支持。

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">

  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>文本转换语音-ttasp</title>
  7.     <style>
  8.         body {
  9.             font-family: Arial, sans-serif;
  10.             text-align: center;
  11.             margin: 50px;
  12.         }

  13.         #output {
  14.             margin-bottom: 20px;
  15.         }

  16.         #text-input {
  17.             width: 80%;
  18.             padding: 15px;
  19.             font-size: 18px;
  20.             margin: 20px auto; /* 居中并且设置上下边距 */
  21.             /* 设置文本框为至少5行 */
  22.             rows: 5;
  23.         }

  24.         #convert-button {
  25.             padding: 15px 40px;
  26.             font-size: 18px;
  27.         }
  28.     </style>
  29. </head>

  30. <body>
  31.     <h1>文本转换语音</h1>
  32.     <button id="convert-button">转换语音</button>
  33.     <br><br>
  34.     <textarea id="text-input" placeholder="请输入文本" rows="5"></textarea>
  35.     <div id="output"></div>

  36.     <script>
  37.         document.getElementById("convert-button").addEventListener("click", function () {
  38.             var textInput = document.getElementById("text-input");
  39.             var text = textInput.value;
  40.             var outputDiv = document.getElementById("output");

  41.             // 使用SpeechSynthesis API将文本转换为语音
  42.             var utterance = new SpeechSynthesisUtterance(text);
  43.             speechSynthesis.speak(utterance);

  44.             // 在页面上显示转换的文本
  45.             outputDiv.innerText = "转换的语音: " + text;

  46.             // 清空输入框
  47.             textInput.value = "";
  48.         });
  49.     </script>
  50. </body>

  51. </html>
复制代码


微信截图_20231120165526.png
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表

在线客服

售前咨询
售后咨询
服务热线
023-58418553
微信公众号