#星光不负 码向未来# 鸿蒙开发实战:基于 CoreSpeechKit 实现文本转语音功能 原创

来个OK
发布于 2025-10-22 22:19
浏览
0收藏

在鸿蒙应用开发中,为应用添加语音交互能力能显著提升用户体验。本文将带你快速掌握基于鸿蒙 CoreSpeechKit 实现文本转语音(TTS)的核心技术,通过三步即可让你的应用 “开口说话”。

一、认识鸿蒙TTS核心能力

鸿蒙系统内置的CoreSpeechKit提供了强大的文本转语音能力,其核心优势在于:
离线可用:支持无网络环境下运行,特别适合无障碍场景

  • 多语言支持:涵盖中文(简繁体)、英文及数字播报
  • 丰富音色:提供聆小珊(女声)、凌飞哲(男声)、劳拉(英语女声)三种音色
  • 高容量处理:单篇文本支持最长 10000 字转换
    #星光不负 码向未来#  鸿蒙开发实战:基于 CoreSpeechKit 实现文本转语音功能-鸿蒙开发者社区

这项能力基于系统级 AI 模块构建,与华为 “小艺” 语音助手同源,稳定性和兼容性经过严格验证,完全适配鸿蒙 Next 系统。

二、3步实现文本转语音功能

实现原理,要初始化文本转语言的引擎(TextToSpeechEngine),然后给它配置参数、配置回调;然后就可以使用它进行操作了,让它干活了。

1. 创建TTS引擎实例

首先需要初始化TextToSpeechEngine引擎,通过配置基础参数确定语言、音色等核心属性;调用createEngine接口,创建TextToSpeechEngine实例。并初始化引擎。使用callback异步回调。

  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}.`);
      }
    });
  }

2. 配置播报参数与回调

引擎创建后,需要设置播报监听回调,用于处理播报开始、完成、错误等状态;得到TextToSpeechEngine实例对象后,实例化SpeakParams对象、SpeakListener对象,并传入待合成及播报的文本originalText,调用speak接口进行播报。

  initParam(){
    // 设置speak的回调信息
     this.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(this.speakListener);

  }

3. 实现播报与控制功能

让它干活,调用播报方法,开发者可以通过修改speakParams主动设置播报策略。最后通过 speak 方法实现文本播报,并提供 stop 方法控制播报过程。

  // 开始播放
  speak(text:string){

    // 设置播报相关参数
    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(),
      extraParams: this.extraParam
    };

    // 调用播报方法
    // 开发者可以通过修改speakParams主动设置播报策略
    this.ttsEngine?.speak(text, this.speakParams);
  }

// 停止播报
stop(){
  // 当服务忙碌时停止播报
  if(this.ttsEngine?.isBusy()){
    this.ttsEngine?.stop();
  }
}

三、实战应用技巧

1. 单例模式全局管理

建议将TTS功能封装为单例类,方便全局调用。我是将上述的方法,整理出了一个单例类TextToSpeechManager,方便在APP中全局使用。

private textToSpeechManger = TextToSpeechManager.getInstance();

2. 页面生命周期集成

在将要进入页面时,在方法aboutToAppear()中进行初始化。确保使用时已就绪。

aboutToAppear() {
  /// 初始化文本转语言引擎
  this.textToSpeechManger.createEngine();
  this.textToSpeechManger.initParam();
}

3.传入文本,生成语音

this.textToSpeechManger.speak('Hello kit');

4.使用技巧

  • 设置停顿,[p500],表示停顿500ms
this.textToSpeechManger.speak('Hello[p500] kit');

四、后记

1.展示(Show your Time)

我不知道怎么上传视频,还是算了吧。就上传一张图片吧。

#星光不负 码向未来#  鸿蒙开发实战:基于 CoreSpeechKit 实现文本转语音功能-鸿蒙开发者社区

2.参考文档

官方文档

3.代码奉上(仅供参考)

import { textToSpeech } from '@kit.CoreSpeechKit';
import { BusinessError } from '@kit.BasicServicesKit';


/**
 * 文本转语音
 * 使用:Core Speech Kit
 * 支持将一篇不超过10000字数的中英文文本(简体中文、繁体中文、数字、英文)合成为语音,并以选定音色进行播报。
 * 场景支持
 * 手机/平板等设备在无网状态下,系统应用无障碍(屏幕朗读)接入文本转语音能力,为视障人士或不方便阅读场景提供播报能力。
 */
export class TextToSpeechManager{
  private static instance: TextToSpeechManager;

  private constructor() {}

  public static getInstance(): TextToSpeechManager {
    if (!TextToSpeechManager.instance) {
      TextToSpeechManager.instance = new TextToSpeechManager();
    }
    return TextToSpeechManager.instance;
  }

  // 创建TextToSpeechEngine实例
  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接口,创建TextToSpeechEngine实例。
   * createEngine接口提供了两种调用形式,当前以其中一种作为示例,其他方式可参考API参考。
   * 其他创建方式:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/hms-ai-texttospeech
   */
  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: ${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(this.speakListener);

  }

  /**
   * 调用播报方法
   * 开发者可以通过修改speakParams主动设置播报策略
   */
  speak(text:string){

    // 设置播报相关参数
    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(),  //'123456', // requestId在同一实例内仅能用一次,请勿重复设置
      extraParams: this.extraParam
    };

    // 调用播报方法
    // 开发者可以通过修改speakParams主动设置播报策略
    this.ttsEngine?.speak(text, this.speakParams);
  }

  /**
   * 停止调用播报方法
   * 当需要停止合成及播报时,可调用stop接口。
   */
  stop(){
    // 当需要查询文本转语音服务是否处于忙碌状态时
    // 才停止播报
    if(this.ttsEngine?.isBusy()){
      this.ttsEngine?.stop();
    }
  }
}


/// 使用实例:

// 1.初始化语言引擎和配置
// private textToSpeechManger = TextToSpeechManager.getInstance();
//
// aboutToAppear() {
//   /// 初始化文本转语言引擎
//   this.textToSpeechManger.createEngine();
//   this.textToSpeechManger.initParam();
// }

// 2.传入文本,生成语音
// this.textToSpeechManger.speak('Hello kit');

// 3.设置停顿 [p500],500ms
// this.textToSpeechManger.speak('Hello[p500] kit');

五、总结

通过本文介绍的方法,你可以快速为鸿蒙应用添加专业级文本转语音功能,无论是无障碍服务、语音助手还是内容播报场景,都能轻松应对。赶紧动手试试,让你的应用 “开口说话” 吧!

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐