欢迎加入开源鸿蒙PC社区:
https://harmonypc.csdn.net/

atomgit仓库地址: https://atomgit.com/m0_66062719/lizhiTTS

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

一、项目概述

在这篇文章将详细介绍如何使用Web Speech API实现一个功能完善的TTS(Text-to-Speech)励志词条朗读应用。通过这篇文章将涵盖了UI设计、TTS技术实现、以及跨平台适配等内容。

1.1 项目目标

  • 实现一个精美的励志词条朗读应用
  • 支持中文TTS语音合成
  • 提供多种参数调节(语速、音调、音量)
  • 分类筛选和历史记录功能
  • 跨平台兼容(HarmonyOS + Electron)

二、技术栈选择

2.1 Web Speech API简介

Web Speech API是一个现代浏览器内置的API,无需额外安装插件或库即可使用,即可实现高质量的语音合成(SpeechSynthesis)和语音识别(SpeechRecognition)。

┌─────────────────────────────────────────────────────────┐
│          Web Speech API                              │
├──────────────────────────┬────────────────────────────┤
│  SpeechSynthesis       │ SpeechRecognition        │
│  (TTS语音合成)      │ 语音识别               │
└──────────────────────────┴────────────────────────────┘

2.2 选择Web Speech API的理由:

  • 浏览器原生支持:现代浏览器内置无需额外安装
  • 简单易用:简洁的API设计
  • 跨浏览器兼容:支持Chrome、Safari、Edge等
  • 离线使用:无需网络连接即可使用
  • 多语言支持:自动使用系统语言包

三、架构设计

3.1 整体架构

┌─────────────────────────────────────────────────────────┐
│                   应用层                           │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────┐ │
│  │  UI  │ │  数据  │ │  TTS  │ │ 历史 │ │
│  │ 层 │ │  管理  │ │  引擎  │ │ 记录  │ │
│  └──┬──┘ └──────┬──┘ └─────┬──┘ └───┬───┘ │
└──────────┼───────────┼──────────┼──────────┘
       │           │           │
       └───────────┼───────────┘
                   ↓
┌─────────────────────────────────────────────────────────┐
│            Web Speech API (SpeecSynthesis)          │
└─────────────────────────────────────────────────────────┘

3.2 核心类设计

class MotivationalApp {
  quotes: Quote[]
  filteredQuotes: Quote[]
  currentQuoteIndex: number
  history: HistoryItem[]
  isSpeaking: boolean
  isAutoPlay: boolean
  synth: SpeechSynthesis
  utterance: SpeechSynthesisUtterance
  rate: number
  pitch: number
  volume: number
}

  speakQuote()  // 朗读
  stopSpeaking() // 停止
  nextQuote()    // 下一条
  // ...其他方法
}

四、UI实现详解

4.1 HTML结构

<!-- 页面头部 -->
<div class="header">
  <h1>✨ 励志词条</h1>
  <p>用声音传递力量</p>
</div>

<!-- 词条卡片 -->
<div class="quote-card">
  <div class="quote-icon">💫</div>
  <div class="quote-content">...内容...</div>
  <div class="quote-author">...作者...</div>
  <div class="quote-category">...分类...</div>
</div>

<!-- 控制面板 -->
<div class="controls">
  <button onclick="app.speakQuote()">🔊 朗读</button>
  <!-- ...
</div>

4.2 CSS视觉设计

采用渐变色主题和毛玻璃效果:

body {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.quote-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24px;
  backdrop-filter: blur(10px);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

五、TTS引擎实现详解

5.1 SpeechSynthesisUtterance

speakQuote() {
  // 1. 创建朗读文本
  const text = `${quote.content} —— ${quote.author}`;
  
  // 2. 创建语音合成实例
  this.utterance = new SpeechSynthesisUtterance(text);
  
  // 3. 设置参数
  this.utterance.rate = this.rate;      // 语速
  this.utterance.pitch = this.pitch;    // 音调
  this.utterance.volume = this.volume;   // 音量
  this.utterance.lang = 'zh-CN';        // 语言
  
  // 4. 选择中文语音
  const voices = this.synth.getVoices();
  const chineseVoice = voices.find(v => v.lang.includes('zh'));
  if (chineseVoice) {
    this.utterance.voice = chineseVoice;
  }
  
  // 5. 绑定事件
  this.utterance.onstart = () => { /* ... */ };
  this.utterance.onend = () => { /* ... */ };
  this.utterance.onerror = () => { /* ... */ };
  
  // 6. 开始朗读
  this.synth.speak(this.utterance);
}

5.2 TTS参数详解

参数 默认值 范围 说明
rate 1.0 0.1 - 10 语速
pitch 1.0 0 - 2 音调
volume 1.0 0 - 1 音量
语速调节
updateRate() {
  this.rate = parseFloat(document.getElementById('rateSlider').value);
  document.getElementById('rateValue').textContent = `${this.rate.toFixed(1)}x`;
}

六、数据管理

6.1 词条数据结构

const quotes = [
  {
    id: 1,
    content: "成功不是终点...",
    author: "温斯顿·丘吉尔",
    category: "courage",
    categoryName: "勇气"
  }
];

6.2 历史记录

addToHistory(quote) {
  // 检查是否存在
  const exists = this.history.find(h => h.id === quote.id);
  if (!exists) {
    this.history.unshift({
      id: quote.id,
      content: quote.content,
      author: quote.author,
      timestamp: Date.now()
    });
    
    // 只保留最近20条
    if (this.history.length > 20) {
      this.history = this.history.slice(0, 20);
    }
    
    this.saveToStorage();
    this.updateHistory();
  }
}

七、事件监听和状态管理

7.1 事件监听

// 开始
this.utterance.onstart = () => {
  this.isSpeaking = true;
  document.getElementById('speakBtn').classList.add('active');
};

// 结束
this.utterance.onend = () => {
  this.isSpeaking = false;
  document.getElementById('speakBtn').classList.remove('active');
  
  // 如果是自动朗读,自动切换下一条
  if (this.isAutoPlay) {
    setTimeout(() => {
      this.nextQuote();
      this.speakQuote();
    }, 1000);
  }
};

// 错误
this.utterance.onerror = () => {
  this.isSpeaking = false;
  // 错误处理
};

7.2 键盘快捷键

setupKeyboardShortcuts() {
  document.addEventListener('keydown', (e) => {
    switch (e.code) {
      case 'Space': 空格
      case 'ArrowRight':case 'KeyS': Scase 'KeyA': A}
  });
}

八、分类筛选功能

8.1 筛选实现

filterByCategory(category) {
  this.currentCategory = category;
  
  const buttons = document.querySelectorAll('.category-btn');
  buttons.forEach(btn => {
    btn.classList.remove('active');
    if (btn.dataset.category === category) {
      btn.classList.add('active');
    }
  });
  
  if (category === 'all') {
    this.filteredQuotes = [...this.quotes];
  } else {
    this.filteredQuotes = this.quotes.filter(q => q.category === category);
  }
  
  this.currentQuoteIndex = 0;
  this.displayQuote();
}

九、LocalStorage存储

9.1 存储和加载

loadFromStorage() {
  try {
    const savedHistory = localStorage.getItem('motivationalHistory');
    if (savedHistory) {
      this.history = JSON.parse(savedHistory);
    }
  } catch (error) {
    console.warn('加载失败:', error);
  }
}

saveToStorage() {
  try {
    localStorage.setItem('motivationalHistory', JSON.stringify(this.history));
  } catch (error) {
    console.warn('保存失败:', error);
  }
}

十、跨平台实现

10.1 HarmonyOS WebEngine

在鸿蒙上直接通过WebEngine运行应用:无需特殊处理,使用Web标准。

10.2 Electron桌面端

// main.js
const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600
  });
  win.loadFile('path/to/index.html');
}

十一、性能优化

11.1 语音选择优化

// 预加载语音
speechSynthesis.onvoiceschanged = () => {
  // 语音加载完成
};

// 避免重复创建
if (!this.synth) {
  this.synth = window.speechSynthesis;
}

十二、扩展功能方向

12.1 可能的扩展功能

  • 语音选择下拉框
  • 保存和分享
  • 播放历史记录
  • 自定义词条
  • 主题切换
  • 多语言支持
  • 定时提醒

十三、总结

通过Web Speech API实现一个功能完善、界面美观的TTS励志词条朗读应用,展示了如何结合现代前端技术打造优秀用户体验。


Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐