首页 > 解决方案 > 如何通过在博客上单击将文本转换为语音

问题描述

我是网络开发的新手。我最近在博客 CMS 上创建了一个博客,我正在尝试编写一个代码,当用户点击它时,它会将文本转换为音频。我在 w3schools / codepen 网站上尝试了以下代码,效果很好。但是当我在我的博客文章中使用它时,它不起作用。你能建议什么是错的。

<audio id="write">
<source src="https://elc101files.000webhostapp.com/write.mp3" type="audio/mpeg">
Your browser does not support the audio element
</audio>
    <a href='#'>
<p onclick="playAudio()" >Write</p>
    </a>
<script type="text/javascript">
var x = document.getElementById("write");
function playAudio() {
  x.play();   
}
</script>

提前致谢。

标签: javascript

解决方案


您需要使用 SpeechSynthesis 将文本转换为音频

像这样

var msg = new SpeechSynthesisUtterance();
msg.text = "Hello World";
window.speechSynthesis.speak(msg); 


//if you want speak with selected text you can do so 

function speakSelection(event) {
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  window.speechSynthesis.speak(`${selection}`) ;
}

document.onselect = speakSelection;


推荐阅读