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

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

前言

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

一、语音合成功能简介

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

1.初始化 TTS 引擎

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

typescript 复制代码
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方法进行语音播报。以下是语音播报的代码:

typescript 复制代码
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方法进行倒计时播报。以下是倒计时播报的代码:

typescript 复制代码
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中的参数,优化语音播报的效果。例如,调整语速、音量、音调等参数,让语音播报更符合用户需求。

typescript 复制代码
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.语音播报内容优化

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

typescript 复制代码
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 引擎初始化失败、语音播报失败等问题。可以通过监听错误回调,及时处理异常情况,提升应用的健壮性。

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

四、总结

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

相关推荐
小草帽学编程38 分钟前
鸿蒙Next开发真机调试签名申请流程
android·华为·harmonyos
陈奕昆41 分钟前
5.2 HarmonyOS NEXT应用性能诊断与优化:工具链、启动速度与功耗管理实战
华为·harmonyos
哼唧唧_5 小时前
React Native开发鸿蒙运动健康类应用的项目实践记录
react native·harmonyos·harmony os5·运动健康
二流小码农12 小时前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
坚果的博客12 小时前
uniappx插件nutpi-idcard 开发与使用指南(适配鸿蒙)
华为·harmonyos
程序员小刘12 小时前
【HarmonyOS 5】 社交行业详解以及 开发案例
华为·harmonyos
软件测试小仙女12 小时前
鸿蒙APP测试实战:从HDC命令到专项测试
大数据·软件测试·数据库·人工智能·测试工具·华为·harmonyos
Raink老师12 小时前
鸿蒙任务项设置案例实战
harmonyos·鸿蒙·案例实战
程序员小刘12 小时前
【HarmonyOS 5】 影视与直播详以及 开发案例
华为·harmonyos
程序员小刘13 小时前
鸿蒙【HarmonyOS 5】 (React Native)的实战教程
react native·华为·harmonyos