当前位置:首页 > JavaScript

js实现tts

2026-02-01 20:48:25JavaScript

使用Web Speech API实现TTS

Web Speech API提供了浏览器内置的文本转语音(TTS)功能,无需额外依赖库。以下是一个基础实现示例:

// 创建语音合成对象
const synth = window.speechSynthesis;

// 获取浏览器支持的语音列表(可选)
const voices = synth.getVoices();

// 基础TTS函数
function speak(text, lang = 'en-US') {
  if (synth.speaking) synth.cancel(); // 停止当前播放

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = lang; // 设置语言
  utterance.rate = 1.0;  // 语速(0.1-10)
  utterance.pitch = 1.0; // 音高(0-2)

  // 选择特定语音(可选)
  if (voices.length > 0) {
    const targetVoice = voices.find(voice => 
      voice.lang.includes(lang)
    );
    if (targetVoice) utterance.voice = targetVoice;
  }

  synth.speak(utterance);
}

// 调用示例
speak('Hello world');

语音参数调整

可以修改SpeechSynthesisUtterance对象的属性来控制语音输出:

const utterance = new SpeechSynthesisUtterance();
utterance.text = '可调节参数的语音';
utterance.volume = 0.8;    // 音量(0-1)
utterance.rate = 0.9;      // 慢速
utterance.pitch = 1.5;     // 高音调
utterance.lang = 'zh-CN';  // 中文

// 添加事件监听
utterance.onboundary = (e) => {
  console.log(`到达边界: ${e.charIndex}处`);
};

多语言支持

通过切换lang属性支持不同语言:

// 英语
speak('Good morning', 'en-US');

// 中文
speak('早上好', 'zh-CN');

// 日语
speak('おはようございます', 'ja-JP');

浏览器兼容性处理

添加兼容性检查和错误处理:

function safeSpeak(text) {
  if (!('speechSynthesis' in window)) {
    console.error('浏览器不支持Web Speech API');
    return;
  }

  try {
    const utterance = new SpeechSynthesisUtterance(text);
    window.speechSynthesis.speak(utterance);
  } catch (e) {
    console.error('语音合成失败:', e);
  }
}

高级功能实现

实现队列系统和语音切换:

const speechQueue = [];
let isSpeaking = false;

function queueSpeak(text, options = {}) {
  speechQueue.push({ text, options });
  if (!isSpeaking) processQueue();
}

function processQueue() {
  if (speechQueue.length === 0) {
    isSpeaking = false;
    return;
  }

  isSpeaking = true;
  const { text, options } = speechQueue.shift();
  const utterance = new SpeechSynthesisUtterance(text);

  Object.assign(utterance, options);
  utterance.onend = processQueue;

  speechSynthesis.speak(utterance);
}

注意事项

  1. Chrome需要用户交互(如点击事件)后才能触发语音合成
  2. 移动端浏览器可能存在限制
  3. 语音列表需要等待voiceschanged事件触发后才能获取完整列表
  4. 部分语言/方言需要操作系统支持对应语音包

js实现tts

标签: jstts
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swip…

js 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Paren…