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

HarmonyOS运动语音开发:如何让运动开始时的语音播报更温暖

##鸿蒙核心技术##运动开发##Core Speech Kit(基础语音服务)#

前言

在运动类应用中,语音播报功能不仅可以提升用户体验,还能让运动过程更加生动有趣。想象一下,当你准备开始运动时,一个温暖的声音提醒你“3,2,1,运动开始了”,是不是比冷冰冰的文字提示更有动力呢?本文将结合鸿蒙(HarmonyOS)开发实战经验,深入解析如何实现运动开始时的语音播报功能,让每一次运动都充满活力。

一、语音合成功能简介

鸿蒙系统提供了强大的语音合成(Text-to-Speech,TTS)功能,可以将文字转换为语音。通过调用鸿蒙的 TTS API,我们可以轻松实现语音播报功能。以下是实现语音播报功能的核心代码:
在这里插入图片描述

1.初始化 TTS 引擎

在使用 TTS 功能之前,我们需要初始化 TTS 引擎。以下是初始化 TTS 引擎的代码:

private ttsEngine?: textToSpeech.TextToSpeechEngine;private async initTtsEngine() {try {// 设置创建引擎参数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;// 设置speak的回调信息let speakListener: textToSpeech.SpeakListener = {// 开始播报回调onStart(requestId: string, response: textToSpeech.StartResponse) {console.info(`onStart, requestId: ${requestId} response: ${JSON.stringify(response)}`);},// 合成完成及播报完成回调onComplete(requestId: string, response: textToSpeech.CompleteResponse) {console.info(`onComplete, requestId: ${requestId} response: ${JSON.stringify(response)}`);},// 停止播报回调onStop(requestId: string, response: textToSpeech.StopResponse) {console.info(`onStop, requestId: ${requestId} response: ${JSON.stringify(response)}`);},// 返回音频流onData(requestId: string, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) {console.info(`onData, requestId: ${requestId} sequence: ${JSON.stringify(response)} audio: ${JSON.stringify(audio)}`);},// 错误回调onError(requestId: string, errorCode: number, errorMessage: string) {console.error(`onError, requestId: ${requestId} errorCode: ${errorCode} errorMessage: ${errorMessage}`);}};// 设置回调this.ttsEngine?.setListener(speakListener);} else {console.error(`Failed to create engine. Code: ${err.code}, message: ${err.message}.`);}});} catch (error) {console.error('Failed to initialize TTS engine:', error);}
}

2.语音播报

初始化 TTS 引擎后,我们可以使用speak方法进行语音播报。以下是语音播报的代码:

private async speak(text: string) {if (!this.ttsEngine) {await this.initTtsEngine();}try {let extraParam: Record<string, Object> ={"queueMode": 0,"speed": 1,"volume": 2,"pitch": 1,"languageContext": 'zh-CN',"audioType": "pcm", "soundChannel": 3, "playType": 1 };let speakParams: textToSpeech.SpeakParams = {requestId: USystem.generateRandomString(5), // requestId在同一实例内仅能用一次,请勿重复设置extraParams: extraParam};// 调用播报方法// 开发者可以通过修改speakParams主动设置播报策略this.ttsEngine?.speak(text, speakParams);} catch (error) {console.error('TTS speak error:', error);}
}

3.调用语音播报

在运动开始时,我们可以通过定时器调用speak方法进行倒计时播报。以下是倒计时播报的代码:

private startCountdown() {let timer = setInterval(() => {if (this.countdownValue > 0) {this.speak(this.countdownValue.toString());this.countdownValue--;} else {clearInterval(timer);this.isCountdownFinished = true;this.speak('运动开始了');this.runTracker.start();}}, 1000);
}

二、代码核心点解析

1.初始化 TTS 引擎

createEngine:创建 TTS 引擎实例。需要设置语言、发音人、在线模式等参数。

setListener:设置语音播报的回调监听器,包括开始、完成、停止、错误等回调。

2.语音播报

speak:调用 TTS 引擎的speak方法进行语音播报。可以通过extraParams设置播报参数,如语速、音量、音调等。

3.倒计时播报

setInterval:使用定时器实现倒计时功能。

clearInterval:倒计时结束后,清除定时器,避免资源浪费。

三、优化与改进

1.语音播报参数优化

可以通过调整extraParams中的参数,优化语音播报的效果。例如,调整语速、音量、音调等参数,让语音播报更符合用户需求。

let extraParam: Record<string, Object> ={"queueMode": 0,"speed": 1.2, // 语速稍快"volume": 2, // 音量稍大"pitch": 1.1, // 音调稍高"languageContext": 'zh-CN',"audioType": "pcm", "soundChannel": 3, "playType": 1 };

2.语音播报内容优化

可以将倒计时播报内容从简单的数字改为更友好的提示语,提升用户体验。例如:

private startCountdown() {let timer = setInterval(() => {if (this.countdownValue > 0) {this.speak(`倒计时 ${this.countdownValue}`);this.countdownValue--;} else {clearInterval(timer);this.isCountdownFinished = true;this.speak('运动正式开始,请做好准备');this.runTracker.start();}}, 1000);
}

3.语音播报异常处理

在实际开发中,可能会遇到 TTS 引擎初始化失败、语音播报失败等问题。可以通过监听错误回调,及时处理异常情况,提升应用的健壮性。

onError(requestId: string, errorCode: number, errorMessage: string) {console.error(`onError, requestId: ${requestId} errorCode: ${errorCode} errorMessage: ${errorMessage}`);// 可以在这里处理错误,例如重新初始化 TTS 引擎
}

四、总结

通过鸿蒙的 TTS 功能,我们可以轻松实现运动开始时的语音播报功能。

http://www.xdnf.cn/news/12442.html

相关文章:

  • 【MySQL基础】数据库的备份与还原
  • 第三章支线一 ·原能之核:语法起源
  • Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践
  • 【Python训练营打卡】day45 @浙大疏锦行
  • k8s下离线搭建elasticsearch
  • 力扣100-移动0
  • Jmeter如何进行多服务器远程测试?
  • Podman 和 Docker
  • 关于如何使用VScode编译下载keil工程的步骤演示
  • BugKu Web渗透之网站被hei(仅仅是ctf题目名称)
  • Three.js中AR实现详解并详细介绍基于图像标记模式AR生成的详细步骤
  • CSS中justify-content: space-between首尾贴边中间等距(两端元素紧贴左右边缘,中间元素等距均匀分布)
  • NLP学习路线图(二十七):Transformer编码器/解码器
  • 传输层:udp与tcp协议
  • 分布式微服务系统架构第144集:FastAPI全栈开发教育系统
  • 基于 Vue 和 Spring Boot 实现滑块验证码的机器验证
  • Linux编程:1、文件编程
  • AI预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月6日第100弹
  • pdf2zh 简明本地部署和api调用,以及离线部署总结
  • 行业案例 | ASOS 借助 Azure AI Foundry(国际版)为年轻时尚爱好者打造惊喜体验
  • 在Windows下利用LoongArch-toolchain交叉编译Qt
  • QuaggaJS用法详解
  • 分布式协同自动化办公系统-工作流引擎-流程设计
  • aardio 简单网页自动化
  • 命令行以TLS/SSL显式加密方式访问FTP服务器
  • 应用分享 | 精准生成和时序控制!AWG在确定性三量子比特纠缠光子源中的应用
  • http头部注入攻击
  • MySQL基础(二)SQL语言、客户端工具
  • 中国首套1公里高分辨率大气湿度指数数据集(2003~2020)
  • 服务器健康摩尔斯电码:深度解读S0-S5状态指示灯