Home > Web Front-end > JS Tutorial > body text

How to convert text to sound using JavaScript

藏色散人
Release: 2021-07-13 16:00:19
Original
4012 people have browsed it

How to implement text-to-speech using JavaScript: first create an HTML sample file; then add js code; and finally use the SpeechSynthesisUtterance interface to synthesize the specified text into the corresponding speech.

How to convert text to sound using JavaScript

The operating environment of this article: Windows 7 system, javascript1.8.5, Dell G3 computer.

How to convert text to sound in JavaScript?

js text-to-speech playback

SpeechSynthesisUtterance

SpeechSynthesisUtterance is a new API in HTML5 for Synthesize the specified text into the corresponding speech. It also includes some configuration items to specify how to read (language, volume, tone), etc.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="textMsg" value="有新的订单,请及时处理">
  <button onclick="speak()">播放</button>
  <button onclick="pause()">暂停</button>
  <button onclick="resume()">继续播放</button>
  <button onclick="cancel()">取消播放</button>
  <script>
    var speech = new SpeechSynthesisUtterance();
    // 播放
    function speak() {
      // speech.pitch = 1 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)
      // speech.rate  = 5 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)
      // speech.voice = 10 // 获取并设置说话的声音
      // speech.volume = 1 // 获取并设置说话的音量
      // speech.lang = speechSynthesis.getVoices()[0] // 设置播放语言,测试没效果
      // speech.cancel() // 删除队列中所有的语音.如果正在播放,则直接停止
      speech.text = textMsg.value // 获取并设置说话时的文本
      speechSynthesis.speak(speech);
    }
    // 暂停
    function pause() {
      speechSynthesis.pause()
    }
    // 继续播放
    function resume() {
      speechSynthesis.resume()
    }
    // 取消播放
    function cancel() {
      speechSynthesis.cancel()
    }
  </script>
</body>
</html>
Copy after login

tips: If there is no sound during playback, you can try restarting the browser to play

Recommended study: "javascript advanced tutorial"

The above is the detailed content of How to convert text to sound using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!