javascript - 如何通过在博客上单击将文本转换为语音
问题描述
我是网络开发的新手。我最近在博客 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>
提前致谢。
解决方案
您需要使用 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;
推荐阅读
- asp.net - 图片标题 - 资源应使用缓存清除,但 URL 与配置的模式不匹配
- azure - 备份 Windows 服务器 Azure VM 新 Azure 恢复服务 Vault 错误代码 BMSUserErrorContainerObjectNotFound
- python - 在 pyqt5 小部件中更新 matplotlib
- google-calendar-api - Google Calendar API - 修改以下所有实例(更新自我与会者响应状态)
- javascript - Javascript 拖放更改 div dragDrop
- ssh - 需要帮助查找用于沉浸式实验室 Going Places 的 SSH 令牌
- python - 通过 pandas 与 pyarrow 转换模式
- python - 如何转置 pyspark 数据帧?
- laravel - 带有 Laravel 和 Vue2 的 InertiaJS:无法重新定义属性:$inertia
- python-3.x - 函数 - 变量 - 范围