当前位置:首页 > JavaScript

js实现文字转语音

2026-01-30 19:32:49JavaScript

实现文字转语音的方法

在JavaScript中,可以通过Web Speech API实现文字转语音(TTS)功能。以下是一个简单的实现方法:

// 创建SpeechSynthesisUtterance对象
const utterance = new SpeechSynthesisUtterance();
utterance.text = "这是要转换为语音的文字内容";

// 设置语音参数(可选)
utterance.rate = 1; // 语速 (0.1-10)
utterance.pitch = 1; // 音高 (0-2)
utterance.volume = 1; // 音量 (0-1)

// 获取可用的语音列表并选择(可选)
const voices = window.speechSynthesis.getVoices();
utterance.voice = voices[0]; // 选择第一个可用语音

// 播放语音
window.speechSynthesis.speak(utterance);

完整示例代码

<!DOCTYPE html>
<html>
<head>
    <title>文字转语音示例</title>
</head>
<body>
    <textarea id="textToSpeak" rows="4" cols="50">输入要转换为语音的文字</textarea>
    <br>
    <button onclick="speak()">朗读</button>
    <button onclick="stop()">停止</button>

    <script>
        function speak() {
            const text = document.getElementById('textToSpeak').value;
            const utterance = new SpeechSynthesisUtterance(text);

            // 可选:设置语音参数
            utterance.rate = 1;
            utterance.pitch = 1;

            window.speechSynthesis.speak(utterance);
        }

        function stop() {
            window.speechSynthesis.cancel();
        }
    </script>
</body>
</html>

注意事项

浏览器兼容性:Web Speech API在现代浏览器中得到良好支持,包括Chrome、Firefox、Edge和Safari,但在旧版浏览器中可能不可用。

语音加载:某些浏览器可能需要等待语音引擎加载完成。可以监听voiceschanged事件:

window.speechSynthesis.onvoiceschanged = function() {
    const voices = window.speechSynthesis.getVoices();
    // 现在可以安全地选择语音
};

高级用法

可以创建更复杂的TTS应用,包括:

  • 语音选择下拉菜单
  • 语速、音高和音量控制滑块
  • 多语言支持
  • 语音队列管理
// 语音选择示例
function populateVoiceList() {
    const voices = window.speechSynthesis.getVoices();
    const voiceSelect = document.getElementById('voiceSelect');

    voices.forEach((voice, i) => {
        const option = document.createElement('option');
        option.textContent = `${voice.name} (${voice.lang})`;
        option.setAttribute('data-voice-index', i);
        voiceSelect.appendChild(option);
    });
}

// 在voiceschanged事件中调用
window.speechSynthesis.onvoiceschanged = populateVoiceList;

替代方案

如果Web Speech API不满足需求,可以考虑:

js实现文字转语音

  • 使用第三方TTS API服务
  • 后端TTS解决方案
  • 专门的TTS JavaScript库

这些方法通常需要网络连接或服务器支持,但可能提供更高质量的语音输出。

标签: 语音文字
分享给朋友:

相关文章

vue实现文字按钮

vue实现文字按钮

Vue 实现文字按钮的方法 在 Vue 中实现文字按钮可以通过多种方式完成,以下是几种常见的方法: 使用原生 HTML 按钮元素 可以通过 <button> 标签结合 CSS 样式实现文…

vue 实现文字动画

vue 实现文字动画

Vue 实现文字动画的方法 使用 CSS 动画结合 Vue 过渡 Vue 的 <transition> 组件可以与 CSS 动画结合,实现文字的动态效果。例如淡入淡出: <tran…

vue实现语音通话

vue实现语音通话

Vue 实现语音通话的技术方案 在 Vue 中实现语音通话需要结合 WebRTC(Web Real-Time Communication)技术,以下是关键步骤和代码示例。 引入 WebRTC 库 使…

vue实现文字向上滚动

vue实现文字向上滚动

vue实现文字向上滚动的方法 使用Vue实现文字向上滚动效果可以通过多种方式实现,以下是几种常见的方法: 使用CSS动画实现 通过CSS的animation和transform属性结合Vue的模板绑…

vue如何实现文字高亮

vue如何实现文字高亮

实现文字高亮的方法 在Vue中实现文字高亮通常可以通过以下几种方式完成,具体取决于需求场景: 使用v-html指令 通过动态绑定HTML内容,将需要高亮的文字包裹在<span>标签中并…

vue实现点击文字变大

vue实现点击文字变大

实现点击文字变大的方法 在Vue中实现点击文字变大的效果,可以通过动态绑定样式或类名来实现。以下是几种常见的方法: 方法一:使用动态绑定style 通过绑定fontSize样式属性,点击时改变字体…