当前位置:首页 > 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,但在旧版浏览器中可能不可用。

js实现文字转语音

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

js实现文字转语音

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不满足需求,可以考虑:

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

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

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

相关文章

vue 实现文字动画

vue 实现文字动画

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

vue实现文字输出

vue实现文字输出

Vue实现文字输出的方法 使用插值表达式 在Vue模板中,可以通过双大括号{{}}插入动态文本。这种方式适合简单的文本绑定。 <template> <div>{{ mes…

vue语音文件播放实现

vue语音文件播放实现

实现语音文件播放的方法 在Vue中实现语音文件播放可以通过HTML5的<audio>元素或JavaScript的Audio对象来完成。以下是几种常见的实现方式。 使用HTML5的audi…

vue实现文字动态输出

vue实现文字动态输出

Vue 实现文字动态输出 使用 v-html 指令动态渲染 HTML 在 Vue 中可以通过 v-html 指令动态渲染包含 HTML 标签的字符串。适用于需要动态插入带格式的文本场景。 <t…

vue如何实现语音叫号

vue如何实现语音叫号

Vue 实现语音叫号功能 准备工作 确保项目中已安装必要的依赖,如 Web Speech API 或第三方语音合成库(如 speak-tts)。浏览器需支持 SpeechSynthesis API(现…

使用vue实现语音通话

使用vue实现语音通话

使用 Vue 实现语音通话 准备工作 确保项目已安装 Vue 3 和必要的依赖。语音通话功能通常需要 WebRTC 技术,因此需要引入相关库(如 peerjs 或 simple-peer)以及后端信令…