干货分享:HarmonyOS Next 如何实现语音朗读能力 原创 精华

全栈若城
发布于 2025-9-3 10:03
浏览
1收藏

干货分享:HarmonyOS Next 如何实现语音朗读能力

前言

大家好,我是若城。本系列旨在帮助开发者快速实现HarmonyOS Next应用中的常用功能,提供即拿即用的代码示例。

本文将重点讲解如何借助HarmonyOS Next的textToSpeech API实现语音朗读能力,让您的应用具备文本转语音的功能。

效果预览

如下图所示,点击案例中的"朗读文本"按钮,即可将页面中的文案进行语音播报:
干货分享:HarmonyOS Next 如何实现语音朗读能力-鸿蒙开发者社区

朗读文本函数封装

为了便于复用和管理,我们在项目的utils文件夹下新建一个textToSpeech.ets文件,用于封装语音朗读相关的功能:
干货分享:HarmonyOS Next 如何实现语音朗读能力-鸿蒙开发者社区

核心工具类

下面是完整的TextToSpeechManager工具类,采用单例模式设计,可以直接复制使用:

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();
        }
    }
}


实际应用步骤

第一步:导入工具类

在需要使用语音朗读功能的页面中,首先导入我们封装好的工具类:

import {TextToSpeechManager} from  "../utils/textToSpeech"

第二步:初始化TTS引擎

在页面的生命周期方法中进行初始化操作。页面打开时需要创建TextToSpeechEngine实例以及实例化相关参数对象:

   private textToSpeechManger = TextToSpeechManager.getInstance();
  aboutToAppear(): void {
        this.textToSpeechManger.createEngine();
        this.textToSpeechManger.initParam();
    }

第三步:实现朗读功能

接下来编写语音朗读的业务函数。当用户点击按钮时,直接将需要播报的文本传入到函数中即可实现语音朗读:

    // 语音朗读
    textToSpeech(txt:string){
        this.textToSpeechManger.speak(txt);
    }

功能特性

  • 多语言支持:支持中英文混合文本朗读
  • 离线使用:无需网络连接即可使用
  • 文本限制:单次最多支持10,000字符
  • 音色选择:支持多种音色配置
  • 参数调节:可调节语速、音量、音调等参数
  • 状态回调:提供完整的播放状态监听

使用建议

  1. 资源管理:建议在页面销毁时调用stop()方法释放资源
  2. 错误处理:可以根据回调函数中的错误信息进行相应的错误处理
  3. 用户体验:长文本建议分段播放,避免用户等待时间过长
  4. 权限配置:确保应用已获得必要的音频权限

总结

通过本文的介绍,我们学习了如何在HarmonyOS Next应用中实现语音朗读功能:

  1. 工具类封装:使用单例模式封装了TextToSpeechManager类,便于全局使用
  2. 引擎初始化:通过createEngine()方法创建TTS引擎实例
  3. 参数配置:通过initParam()方法设置播报参数和回调监听
  4. 朗读实现:通过speak()方法实现文本转语音功能
  5. 资源控制:通过stop()方法控制播放状态

这套语音朗读解决方案具有良好的封装性和易用性,可以快速集成到您的HarmonyOS Next项目中。无论是新闻阅读、学习辅助还是无障碍功能,都能提供优秀的用户体验。 好了文本朗读到这里就结束, 赶快去体验吧!

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