Home >Web Front-end >JS Tutorial >How to convert text to sound using JavaScript

How to convert text to sound using JavaScript

藏色散人
藏色散人Original
2021-07-13 16:00:194132browse

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>

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!

Statement:
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