鸿蒙应用开发之文本转语音基础

仿佛云烟
发布于 2025-6-28 17:06
浏览
0收藏

一、工具


鸿蒙应用开发之文本转语音基础-鸿蒙开发者社区

DevEco Studio



二、项目介绍


根据Core Speech Kit播放不超过10000字符的中文文本


1.在使用文本转语音时,将实现文本转语音相关的类添加至工程。



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


2.调用createEngine接口,创建​​TextToSpeechEngine​​实例。


let ttsEngine: textToSpeech.TextToSpeechEngine;

// 设置创建引擎参数
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');
    // 接收创建引擎的实例
    ttsEngine = textToSpeechEngine;
  } else {
    console.error(Failed to create engine. Code: ${err.code}, message: ${err.message}.);
  }
});


3.得到​​TextToSpeechEngine​​​实例对象后,实例化​​SpeakParams​​​对象、​​SpeakListener​​​对象,并传入待合成及播报的文本originalText,调用​​speak​​接口进行播报。


// 设置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});
  }
};
// 设置回调
ttsEngine.setListener(speakListener);
let originalText: string = 'Hello HarmonyOS';
// 设置播报相关参数
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: '123456', // requestId在同一实例内仅能用一次,请勿重复设置
  extraParams: extraParam
};
// 调用播报方法
// 开发者可以通过修改speakParams主动设置播报策略
ttsEngine.speak(originalText, speakParams);



整体代码:


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

let ttsEngine: textToSpeech.TextToSpeechEngine;
@Entry
@Component
struct Index {
  @State createCount: number = 0;
  @State voiceInfo: string = "";
  @State originalText: string = "\n\t\t海上生明月,天涯共此时。\n\t\t" +
    "情人怨遥夜,竟夕起相思。\n\t\t";

  aboutToAppear(): void {
    this.createCount++;
    this.createByCallback();
    this.listVoicesCallback()
  }


  build() {
    Column() {
      Scroll() {
        Column() {
          TextArea({ placeholder: 'Please enter tts original text', text: ${this.originalText} })
            .margin(20)
            .focusable(true)
            .onChange((value: string) => {
              this.originalText = value;
            })


          Button() {
            Text("文本转语音")
              .fontColor(Color.White)
              .fontSize(20)
          }
          .type(ButtonType.Capsule)
          .backgroundColor("#0x317AE7")
          .width("80%")
          .height(50)
          .margin(10)
          .onClick(() => {
            this.createCount++;
            this.speak();
          })


          Button() {
            Text("停止")
              .fontColor(Color.White)
              .fontSize(20)
          }
          .type(ButtonType.Capsule)
          .backgroundColor("#0x317AE7")
          .width("80%")
          .height(50)
          .margin(10)
          .onClick(() => {
            // 停止播报
            console.info("Stop button clicked.");
            ttsEngine.stop();
          })


          Button() {
            Text("关闭")
              .fontColor(Color.White)
              .fontSize(20)
          }
          .type(ButtonType.Capsule)
          .backgroundColor("#0x317AA7")
          .width("80%")
          .height(50)
          .margin(10)
          .onClick(() => {
            // 释放引擎
            ttsEngine.shutdown();
          })
        }
        .layoutWeight(1)
      }
      .width('100%')
      .height('100%')
    }
  }

  // 创建引擎,通过callback形式返回
  private createByCallback() {
    // 设置创建引擎参数
    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.');
        // 接收创建引擎的实例
        ttsEngine = textToSpeechEngine;
      } else {
        console.error(Failed to create engine. Code: ${err.code}, message: ${err.message}.);
      }
    });
  };

  // 调用speak播报方法
  private 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)});
      },
      // 停止播报完成回调,调用stop方法并完成时会触发此回调
      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});
      }
    };
    // 设置回调
    ttsEngine.setListener(speakListener);
    // 设置播报相关参数
    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: '123456-a', // requestId在同一实例内仅能用一次,请勿重复设置
      extraParams: extraParam
    };
    // 调用speak播报方法
    ttsEngine.speak(this.originalText, speakParams);
  };

  // 查询语种音色信息,以callback形式返回
  private listVoicesCallback() {
    // 设置查询相关参数
    let voicesQuery: textToSpeech.VoiceQuery = {
      requestId: '123456-b', // requestId在同一实例内仅能用一次,请勿重复设置
      online: 1
    };

    // 调用listVoices方法,以callback返回语种音色查询结果
    ttsEngine.listVoices(voicesQuery, (err: BusinessError, voiceInfo: textToSpeech.VoiceInfo[]) => {
      if (!err) {
        // 接收目前支持的语种音色等信息
        this.voiceInfo = JSON.stringify(voiceInfo);
        console.info(Succeeded in listing voices, voiceInfo is ${voiceInfo});
      } else {
        console.error(Failed to list voices. Code: ${err.code}, message: ${err.message});
      }
    });
  };
}


下载Demo体验:​​CoreSpeech1: 鸿蒙应用开发之——文本转语音​









收藏
回复
举报
回复
    相关推荐