当前位置: 首页 > news >正文

HarmonyOS之深入解析如何实现语音朗读能力

一、前言

  • 在 HarmonyOS Next 中为应用添加语音朗读能力,主要依赖于系统提供的 TextToSpeech (TTS) 引擎。那么如何借助 HarmonyOS Next 的 textToSpeech API 实现语音朗读能力,让应用具备文本转语音的功能呢?
  • 实现语音朗读功能,本质上是应用通过 TextToSpeech API 与系统 TTS 服务交互的过程。其核心流程如下:

在这里插入图片描述

二、语音朗读实现流程

① 配置权限与引入模块

  • 在开始编码前,需要在项目的 module.json5 文件中声明必要的权限。根据应用场景,可能需要网络或设备位置权限。
{"module": {"requestPermissions": [{"name": "ohos.permission.INTERNET","reason": "用于在线语音服务"},{"name": "ohos.permission.APPROXIMATE_LOCATION","reason": "语音服务定位"}]}
}
  • 在需要使用的 .ets 文件中,引入相关模块:
import { textToSpeech } from '@kit.CoreSpeechKit'; // 引入CoreSpeechKit
import { BusinessError } from '@kit.BasicServicesKit';

② 创建与初始化 TTS 引擎

  • 为了便于复用和管理,通常我们会将 TTS 功能封装成一个独立的管理类,例如 TextToSpeechManager,并采用单例模式确保全局唯一。在项目的 utils 文件夹下新建一个 TextToSpeechManager.ets 文件,用于封装语音朗读相关的功能:

在这里插入图片描述

  • 需要引入如下的头文件:
import { textToSpeech } from '@kit.CoreSpeechKit';
import { BusinessError } from '@kit.BasicServicesKit';
  • 初始化单例和参数:
export class TextToSpeechManager {private static instance: TextToSpeechManager;private constructor() {}public static getInstance():TextToSpeechManager {if (!TextToSpeechManager.instance) {TextToSpeechManager.instance = new TextToSpeechManager();}return TextToSpeechManager.instance;}// 创建TextSpeechEngine实例private ttsEngine : textToSpeech.TextToSpeechEngine | null = null;// 设置播报相关参数private extraParam : Record<string,Object> | null = null;// 实例化SpeakParams对象private speakParams : textToSpeech.SpeakParams | null = null;// SpeakListener对象,设置speak的回调信息private speakListener : textToSpeech.SpeakListener | null = null;createEngine() {// 设置创建引擎参数let extraParam : Record<string,Object> = {"style":'interaction-broadcast',"locate":'CN',"name":'EngineName'};let initParamsInfo : textToSpeech.CreateEngineParams = {language:'zh-CN', // 设置语言person:0,         // 设置发音人online:1,         // 是否使用在线引擎extraParams: extraParam};// 调用createEngine方法textToSpeech.createEngine(initParamsInfo, (err : BusinessError, textToSpeechEngine : textToSpeech.TextToSpeechEngine) => {if (!err) {console.info('Succeeded in creating engine');// 接收创建引擎的实例this.ttsEngine = textToSpeechEngine;} else {console.error(`Failed to create engine. Code:${err.code}, message:${err.message}.`);}});}}

③ 设置监听回调

  • 为了感知语音合成的状态(如开始、结束、出错),需要设置监听回调:
  // 得到TextToSpeechEngine实例对象后,实例化SpeakParams对象、SpeakListener对象,并传入待合成及播报的文本originalText,调用speak接口进行播报。initParam() {// 设置speak的回调信息this.speakListener = {// 开始播报回调onStart(requestId : string, response: textToSpeech.StartResponse) {console.info(`onStart, requestId:${JSON.stringify(requestId)} response: ${JSON.stringify(response)}`);},// 合成完成及播报完成回调onComplete(requestId : string, response: textToSpeech.CompleteResponse) {console.info(`onComplete, requestId:${JSON.stringify(requestId)} response: ${JSON.stringify(response)}`);},onStop(requestId : string, response: textToSpeech.StopResponse) {console.info(`onStop, requestId:${JSON.stringify(requestId)} response: ${JSON.stringify(response)}`);},onData(requestId : string, audio : ArrayBuffer, response : textToSpeech.SynthesisResponse) {console.info(`onData, requestId:${JSON.stringify(requestId)} response: ${JSON.stringify(response)}`);},onError(requestId : string, errorCode : number, errorMessage : string) {console.info(`onError, errorCode:${JSON.stringify(errorCode)} errorMessage: ${JSON.stringify(errorMessage)}`);},};// 设置回调this.ttsEngine?.setListener(this.speakListener);}

④ 执行语音朗读

  • 准备好引擎和监听后,就可以调用 speak 方法进行朗读了。请注意,单次合成的文本长度通常有不超过 10000 个字符的限制:
// 调用播报方法: 可以通过修改speakParams主动设置播报策略speak(text:string) {if (!this.ttsEngine) {console.error('TTS Engine is not initialized');return;}if (!text || text.length > 10000) {console.error('Text is empty or too long');return;}// 设置播报相关参数this.extraParam = {"queueMode":0, "speed": 1, "volume": 0.1, "pitch":1, "languageContext":'zh-CN', "audioType":"pcm", "soundChannel":3,"playType":1};this.speakParams = { requestId:new Date().getTime().toString(), // requestId在同一实例内仅能用一次,请勿重复设置extraParams: this.extraParam };// 调用播报方法:可以通过修改speakParams主动设置播报策略this.ttsEngine?.speak(text, this.speakParams);}

⑤ 控制播放状态

  • 一个完整的朗读功能还需要提供播放控制:
// 停止调用播报方法: 当需要停止合成及播报时,可调用stop接口stop() {if (this.ttsEngine?.isBusy()) {this.ttsEngine?.stop();}}

三、实际应用步骤

  • 首先要导入工具类,在需要使用语音朗读功能的页面中,首先导入封装好的工具类:
import { TextToSpeechManager } from "../utils/TextToSpeechManager"
  • 初始化TTS引擎,在页面的生命周期方法中进行初始化操作,页面打开时需要创建 TextToSpeechEngine 实例以及实例化相关参数对象:
private textToSpeechManger = TextToSpeechManager.getInstance();aboutToAppear(): void {this.textToSpeechManger.createEngine();this.textToSpeechManger.initParam();}
  • 接下来编写语音朗读的业务函数,当用户点击按钮时,直接将需要播报的文本传入到函数中即可实现语音朗读:
this.textToSpeechManger.speak(txt);
  • 特色:
    • 多语言支持:支持中英文混合文本
    • 朗读离线使用:无需网络连接即可
    • 使用文本限制:单次最多支持 10,000 字符
    • 音色选择:支持多种音色
    • 配置参数调节:可调节语速、音量、音调等参数
    • 状态回调:提供完整的播放状态监听
http://www.dtcms.com/a/600613.html

相关文章:

  • 台州企业网站的建设做网站能挣多少钱
  • 网站开发内容包括哪些wordpress 统计代码
  • 【昇腾CANN工程实践】BERT情感分析API性能优化实录:从CPU到NPU的15倍加速
  • 【Linux基础开发工具 (二)】详解Linux文本编辑器:Vim从入门到精通——完整教程与实战指南(上)
  • 使用 BR 备份 TiDB 到阿里云 OSS 存储
  • 机器学习项目——基于集成学习提升树情绪分类(代码/论文)
  • C++ 抽象类与多态原理深度解析:从纯虚函数到虚表机制(附高频面试题)
  • 尚硅谷 SpringCloud 01 分布式概念-工程创建-nacos安装-nacos服务注册与发现 -远程调用
  • C# Sqlite帮助类
  • 传统方式部署 Hadoop 高可用集群
  • 微软 Win11 经典版 Outlook 曝 BUG,加速 SSD 损耗
  • C++在边缘AI加速中的硬件优化:结合位运算与SIMD提升推理效率
  • 网站开发文档撰写作业牡丹江整站优化
  • QT:ItemView视图控件
  • 让UI完全按屏幕比例变化的方法
  • 结项报告完整版:Apache SeaTunnel 支持 Flink 引擎 Schema Evolution 功能
  • 微服务生态组件之Spring Cloud LoadBalancer详解和源码分析
  • 重庆长寿网站设计公司哪家专业网站跳转微信链接
  • 阿里云域名DNS解析URL转发不支持HTTPS?
  • leetcode 2654. 使数组所有元素变成 1 的最少操作次数 中等
  • AI取名大师 | PM2 部署 Bun.js 应用及配置 Let‘s Encrypt 免费 HTTPS 证书
  • 结项报告完整版 | Apache SeaTunnel支持metalake开发
  • 【cursor】进阶技巧Rules
  • WebServer05
  • 【数据分析-Excel】常用函数汇总
  • 深入理解MySQL事务隔离级别与锁机制(从ACID到MVCC的全面解析)
  • RabbitMQ应用(1)
  • .NET驾驭Excel之力:Excel应用程序的创建与管理
  • Unity2.5D视角肉鸽项目架构
  • JAVA和C#的语法对比