HarmonyOS 鸿蒙Next 文本转语音

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 文本转语音

语音播报无法展示,请用真机测试

开发步骤:

一 、创建语音播报对象:textToSpeechEngine实例

二 、 设置语音合成播报回调 speak()、stop()、isBusy()需要设置回调

三 、 合成并播报文本、停止合成或停止播报、判断当前是否处于合成或播报中、

四 、 释放对象

一、创建语音播报对象

定义一个文本转语音的工具,把创建对象,获取实例写成一个方法。把语音播报对象全局化

创建对象:createEngine接口提供了两种调用形式,一种是以回调形式,一种的promise,以下是以promise为示例

核心语法: textToSpeech.createEngine(initParamsInfo)

//文本转语音
import { textToSpeech } from ‘@kit.CoreSpeechKit’;

// 一 、创建语音播报对象() //二 、 设置语音合成播报回调() speak()、stop()、isBusy()需要设置回调 //三 、 合成并播报文本、停止合成或停止播报、判断当前是否处于合成或播报中、 //四 、 释放对象

class TextToSpeech { //实例对象 ttsEngine: textToSpeech.TextToSpeechEngine | null = null

//创建对象 private async Creat() { //判断是否支持文本播报 if (!canIUse(‘SystemCapability.AI.TextToSpeech’)) { AlertDialog.show({ message: ‘当前设备不支持文本播报’ }) return Promise.reject(‘当前设备不支持文本播报’) } else {

  <span class="hljs-comment"><span class="hljs-comment">//判断是否存在引擎</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine) {
    <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine
  }

  <span class="hljs-keyword"><span class="hljs-keyword">try</span></span> {

  <span class="hljs-comment"><span class="hljs-comment">//1、创建语音播报对象的设置信息</span></span>
  <span class="hljs-comment"><span class="hljs-comment">/*
   * 配置信息:
   * language :   必填   语种, 当前仅支持“zh-CN”中文。
   * online ;     必填   模式。0为在线,目前不支持;1为离线,当前仅支持离线模式。
   * person ;     必填   音色。0为小艺女生音色,当前仅支持小艺女生音色。
   * extraParams ;可选   附加参数。
   *    &lt;'style', string&gt; 风格。 可选,不设置时默认为“interaction-broadcast”,当前仅支持“interaction-broadcast” 普通话播报。
   *    &lt;'locate', string&gt; 区域信息。可选,不设置时默认为“CN”,当前仅支持“CN”。CN:中国。
   *    &lt;'name', string&gt; 引擎名称。可选,引擎名称,不设置是默认为空。
   * */</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> initParamsInfo: textToSpeech.CreateEngineParams = {
    language: <span class="hljs-string"><span class="hljs-string">'zh-CN'</span></span>,
    person: <span class="hljs-number"><span class="hljs-number">0</span></span>,
    online: <span class="hljs-number"><span class="hljs-number">1</span></span>,
    <span class="hljs-comment"><span class="hljs-comment">// extraParams: { "style": 'interaction-broadcast', "locate": 'CN', "name": 'EngineName' } //name:引擎名称,可自定义</span></span>
  }


  <span class="hljs-comment"><span class="hljs-comment">//1、创建语音播报对象的设置信息</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">await</span></span> textToSpeech.createEngine(initParamsInfo)

  <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine = ttsEngine

  <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> ttsEngine

  } <span class="hljs-keyword"><span class="hljs-keyword">catch</span></span> (err) {
    <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> Promise.reject(err)
  }

}

} }

export const textTospeech = new TextToSpeech();<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

二、设置语音合成播报回调

通过设置回调,注册监听语音播放过程的所有状态。

执行speak()【文本转语音】、stop()【停止播报】、isBusy()【判断是否处于播报中】方法前,需要设置回调监听

核心语法:ttsEngine.setListener(speakListener);

  //设置语音合成播报回调
private async setListener() {
//获取引擎对象
await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine

<span class="hljs-comment"><span class="hljs-comment">// 设置speak的回调信息</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> speakListener: textToSpeech.SpeakListener = {
  <span class="hljs-comment"><span class="hljs-comment">// 开始合成或播报的回调--返回请求ID、播报相关参数,例如通道数、采样率、采样位数信息</span></span>
  onStart(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.StartResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'开始合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'开始合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 合成完成或播报完成回调--返回请求ID,完成合成或播报相关信息。</span></span>
  onComplete(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.CompleteResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'合成完成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'合成完成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 停止合成或播报回调--表示stop已完成。</span></span>
  onStop(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.StopResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'停止合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'停止合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 返回音频流---返回请求ID,音频流信息,音频附加信息如格式、时长等。若需要返回音频流信息</span></span>
  onData(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) {
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' audio: '</span></span> + audio);
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' audio: '</span></span> + audio);
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 错误回调---返回请求ID、错误码及错误描述。</span></span>
  onError(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, errorCode: number, errorMessage: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>) {
    console.error(<span class="hljs-string"><span class="hljs-string">'错误回调: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' errorCode: '</span></span> + errorCode + <span class="hljs-string"><span class="hljs-string">'errorMessage: '</span></span> + errorMessage);

  }
};
<span class="hljs-comment"><span class="hljs-comment">// 设置回调</span></span>
ttsEngine?.setListener(speakListener);

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

三、功能应用

把文本转语音、停止播报、判断当前是否处于合成或播报中、查询支持的音色信息、关闭引擎 功能都各自封装成一个方法,便于应用

文本转语音:

核心语法:ttsEngine.speak(text, speakParams);

  //功能应用
//合成并播放文本
async speak(text: string,) {
//1、获取引擎对象
await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">// 设置合成参数:speakParams</span></span>
<span class="hljs-comment"><span class="hljs-comment">/*
 *  requestId       必填  合成播报ID,全局不允许重复。
 *  extraParams     可选  合成参数。用于配置语速、音量、音调、合成类型等
 *      &lt;'speed', number&gt; 语速  可选,支持范围[0.5-2],不传参时默认为1
 *      &lt;'volume', number&gt; 音量   可选,支持范围[0-2],不传参时默认为1。
 *      &lt;'languageContext', string&gt; 语境,播放阿拉伯数字用的语种。可选,当前仅支持“zh-CN”中文,不传参时默认“zh-CN”
 *      &lt;'audioType', string&gt; 音频类型  可选,当前仅支持“pcm”,不传参时默认为“pcm”(PCM 即脉冲编码调制 (Pulse Code Modulation))
 *      &lt;'playType', number&gt; 合成类型。可选,不传参时默认为1。 0:仅合成不播报,返回音频流。 1:合成与播报不返回音频流。
 *      &lt;'soundChannel', number&gt; 通道。可选,参数范围0-16,整数类型,可参考音频流使用类型介绍来选择适合自己的音频场景。不传参时默认为3,语音助手通道。
 *      &lt;'queueMode', number&gt; 播报模式。可选,不传参时默认为0。0:排队模式播报。1:抢占模式播报。
 *
 * */</span></span>

<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> extraParam: Record&lt;<span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, Object&gt; = {
  <span class="hljs-string"><span class="hljs-string">"speed"</span></span>: <span class="hljs-number"><span class="hljs-number">1</span></span>,
  <span class="hljs-string"><span class="hljs-string">"volume"</span></span>: <span class="hljs-number"><span class="hljs-number">2</span></span>,
  <span class="hljs-string"><span class="hljs-string">"pitch"</span></span>: <span class="hljs-number"><span class="hljs-number">1</span></span>,
  <span class="hljs-string"><span class="hljs-string">"languageContext"</span></span>: <span class="hljs-string"><span class="hljs-string">'zh-CN'</span></span>,
  <span class="hljs-string"><span class="hljs-string">"audioType"</span></span>: <span class="hljs-string"><span class="hljs-string">"pcm"</span></span>
}

<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> speakParams: textToSpeech.SpeakParams = {
  requestId: Date.now().toString(), <span class="hljs-comment"><span class="hljs-comment">// requestId在同一实例内仅能用一次,请勿重复设置 ----可自行按照唯一性规则生成</span></span>
  <span class="hljs-comment"><span class="hljs-comment">// extraParams: extraParam</span></span>
}
<span class="hljs-comment"><span class="hljs-comment">// 传入文本originalText,调用speak接口</span></span>
ttsEngine?.speak(text, speakParams);

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

停止播报

核心语法:ttsEngine.stop();

  //功能应用
//停止播报
async stop() {
//1、获取引擎对象
await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">//停止播放</span></span>
ttsEngine?.stop();

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

判断是否处于合成或播报中

核心语法:ttsEngine.isBusy();

  //功能应用
//判断当前是否处于合成或播报中
async isBusy() {
//1、获取引擎对象
await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">//true:引擎正处于合成或播报状态。</span></span>
<span class="hljs-comment"><span class="hljs-comment">// false:引擎没有处于合成或播报状态。</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> ttsEngine?.isBusy();

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

查询支持的音色信息

核心语法:ttsEngine.listVoices(voicesQuery)

  //功能应用
//查询支持的音色信息
async GetVoicesList() {

<span class="hljs-comment"><span class="hljs-comment">//获取引擎对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine

<span class="hljs-comment"><span class="hljs-comment">//查询音色</span></span>
<span class="hljs-comment"><span class="hljs-comment">/*  * 配置信息:
 * requestId :   必填   请求ID,全局不允许重复。。
 * online ;     必填   模式。0为在线,目前不支持;1为离线,当前仅支持离线模式。
 * extraParams ;可选   附加参数。
 *    &lt;'person', number&gt; 查询的音色。。 可选,非空时则language必填,当前仅支持0小艺女声音色。
 *    &lt;'language', string&gt; 查询的语种。可选,当前仅支持“zh-CN”中文。
 * */</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> voicesQuery: textToSpeech.VoiceQuery = {
  requestId: Date.now().toString(), <span class="hljs-comment"><span class="hljs-comment">// requestId在同一实例内仅能用一次,请勿重复设置 ----可自行按照唯一性规则生成</span></span>
  online: <span class="hljs-number"><span class="hljs-number">1</span></span>
}

<span class="hljs-comment"><span class="hljs-comment">/*
* language  支持的语种信息。
* person    支持的音色信息。
* style     风格。interaction-broadcast:普通话播报。
* status    目前的使用状态。  GA:可使用状态  EOM:废弃状态
* gender    性别  male:男性 female:女性
* description   语音的描述,角色属性、支持的情感等说明
* */</span></span>

<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> resList = <span class="hljs-keyword"><span class="hljs-keyword">await</span></span> ttsEngine?.listVoices(voicesQuery)
<span class="hljs-comment"><span class="hljs-comment">// 输出音色列表</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> resList

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

关闭引擎,释放引擎资源

核心语法:ttsEngine.shutdown();

  //功能应用
//关闭引擎,释放引擎资源。
async shutdown() {
//1、获取引擎对象
await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine
<span class="hljs-comment"><span class="hljs-comment">// 调用shutdown接口</span></span>
ttsEngine?.shutdown();

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

四、完整封装代码

//文本转语音
import { textToSpeech } from ‘@kit.CoreSpeechKit’;

// 一 、创建语音播报对象() //二 、 设置语音合成播报回调() speak()、stop()、isBusy()需要设置回调 //三 、 合成并播报文本、停止合成或停止播报、判断当前是否处于合成或播报中、 //四 、 释放对象

class TextToSpeech { //实例对象 ttsEngine: textToSpeech.TextToSpeechEngine | null = null

//功能应用 //查询支持的音色信息 async GetVoicesList() {

<span class="hljs-comment"><span class="hljs-comment">//获取引擎对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine

<span class="hljs-comment"><span class="hljs-comment">//查询音色</span></span>
<span class="hljs-comment"><span class="hljs-comment">/*  * 配置信息:
 * requestId :   必填   请求ID,全局不允许重复。。
 * online ;     必填   模式。0为在线,目前不支持;1为离线,当前仅支持离线模式。
 * extraParams ;可选   附加参数。
 *    &lt;'person', number&gt; 查询的音色。。 可选,非空时则language必填,当前仅支持0小艺女声音色。
 *    &lt;'language', string&gt; 查询的语种。可选,当前仅支持“zh-CN”中文。
 * */</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> voicesQuery: textToSpeech.VoiceQuery = {
  requestId: Date.now().toString(), <span class="hljs-comment"><span class="hljs-comment">// requestId在同一实例内仅能用一次,请勿重复设置 ----可自行按照唯一性规则生成</span></span>
  online: <span class="hljs-number"><span class="hljs-number">1</span></span>
}

<span class="hljs-comment"><span class="hljs-comment">/*
* language  支持的语种信息。
* person    支持的音色信息。
* style     风格。interaction-broadcast:普通话播报。
* status    目前的使用状态。  GA:可使用状态  EOM:废弃状态
* gender    性别  male:男性 female:女性
* description   语音的描述,角色属性、支持的情感等说明
* */</span></span>

<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> resList = <span class="hljs-keyword"><span class="hljs-keyword">await</span></span> ttsEngine?.listVoices(voicesQuery)
<span class="hljs-comment"><span class="hljs-comment">// 输出音色列表</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> resList

}

//功能应用 //合成并播放文本 async speak(text: string,) { //1、获取引擎对象 await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">// 设置合成参数:speakParams</span></span>
<span class="hljs-comment"><span class="hljs-comment">/*
 *  requestId       必填  合成播报ID,全局不允许重复。
 *  extraParams     可选  合成参数。用于配置语速、音量、音调、合成类型等
 *      &lt;'speed', number&gt; 语速  可选,支持范围[0.5-2],不传参时默认为1
 *      &lt;'volume', number&gt; 音量   可选,支持范围[0-2],不传参时默认为1。
 *      &lt;'languageContext', string&gt; 语境,播放阿拉伯数字用的语种。可选,当前仅支持“zh-CN”中文,不传参时默认“zh-CN”
 *      &lt;'audioType', string&gt; 音频类型  可选,当前仅支持“pcm”,不传参时默认为“pcm”(PCM 即脉冲编码调制 (Pulse Code Modulation))
 *      &lt;'playType', number&gt; 合成类型。可选,不传参时默认为1。 0:仅合成不播报,返回音频流。 1:合成与播报不返回音频流。
 *      &lt;'soundChannel', number&gt; 通道。可选,参数范围0-16,整数类型,可参考音频流使用类型介绍来选择适合自己的音频场景。不传参时默认为3,语音助手通道。
 *      &lt;'queueMode', number&gt; 播报模式。可选,不传参时默认为0。0:排队模式播报。1:抢占模式播报。
 *
 * */</span></span>

<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> extraParam: Record&lt;<span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, Object&gt; = {
  <span class="hljs-string"><span class="hljs-string">"speed"</span></span>: <span class="hljs-number"><span class="hljs-number">1</span></span>,
  <span class="hljs-string"><span class="hljs-string">"volume"</span></span>: <span class="hljs-number"><span class="hljs-number">2</span></span>,
  <span class="hljs-string"><span class="hljs-string">"pitch"</span></span>: <span class="hljs-number"><span class="hljs-number">1</span></span>,
  <span class="hljs-string"><span class="hljs-string">"languageContext"</span></span>: <span class="hljs-string"><span class="hljs-string">'zh-CN'</span></span>,
  <span class="hljs-string"><span class="hljs-string">"audioType"</span></span>: <span class="hljs-string"><span class="hljs-string">"pcm"</span></span>
}

<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> speakParams: textToSpeech.SpeakParams = {
  requestId: Date.now().toString(), <span class="hljs-comment"><span class="hljs-comment">// requestId在同一实例内仅能用一次,请勿重复设置 ----可自行按照唯一性规则生成</span></span>
  <span class="hljs-comment"><span class="hljs-comment">// extraParams: extraParam</span></span>
}
<span class="hljs-comment"><span class="hljs-comment">// 传入文本originalText,调用speak接口</span></span>
ttsEngine?.speak(text, speakParams);

}

//功能应用 //停止播报 async stop() { //1、获取引擎对象 await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">//停止播放</span></span>
ttsEngine?.stop();

}

//功能应用 //判断当前是否处于合成或播报中 async isBusy() { //1、获取引擎对象 await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine


<span class="hljs-comment"><span class="hljs-comment">//2、设置回调 注册监听</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">await</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.setListener()

<span class="hljs-comment"><span class="hljs-comment">//true:引擎正处于合成或播报状态。</span></span>
<span class="hljs-comment"><span class="hljs-comment">// false:引擎没有处于合成或播报状态。</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> ttsEngine?.isBusy();

}

//功能应用 //关闭引擎,释放引擎资源。 async shutdown() { //1、获取引擎对象 await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine
<span class="hljs-comment"><span class="hljs-comment">// 调用shutdown接口</span></span>
ttsEngine?.shutdown();

}

//设置语音合成播报回调 private async setListener() { //获取引擎对象 await this.Creat()

<span class="hljs-comment"><span class="hljs-comment">//实例对象</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine

<span class="hljs-comment"><span class="hljs-comment">// 设置speak的回调信息</span></span>

<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> speakListener: textToSpeech.SpeakListener = {
  <span class="hljs-comment"><span class="hljs-comment">// 开始合成或播报的回调--返回请求ID、播报相关参数,例如通道数、采样率、采样位数信息</span></span>
  onStart(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.StartResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'开始合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'开始合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 合成完成或播报完成回调--返回请求ID,完成合成或播报相关信息。</span></span>
  onComplete(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.CompleteResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'合成完成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'合成完成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 停止合成或播报回调--表示stop已完成。</span></span>
  onStop(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, response: textToSpeech.StopResponse) {
    console.info(<span class="hljs-string"><span class="hljs-string">'停止合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId);
    console.info(<span class="hljs-string"><span class="hljs-string">'停止合成: '</span></span> + <span class="hljs-string"><span class="hljs-string">'response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 返回音频流---返回请求ID,音频流信息,音频附加信息如格式、时长等。若需要返回音频流信息</span></span>
  onData(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) {
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' audio: '</span></span> + audio);
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' audio: '</span></span> + audio);
    console.log(<span class="hljs-string"><span class="hljs-string">'返回音频流: '</span></span> + <span class="hljs-string"><span class="hljs-string">' response: '</span></span> + JSON.stringify(response));
  },
  <span class="hljs-comment"><span class="hljs-comment">// 错误回调---返回请求ID、错误码及错误描述。</span></span>
  onError(requestId: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>, errorCode: number, errorMessage: <span class="hljs-keyword"><span class="hljs-keyword">string</span></span>) {
    console.error(<span class="hljs-string"><span class="hljs-string">'错误回调: '</span></span> + <span class="hljs-string"><span class="hljs-string">'requestId: '</span></span> + requestId + <span class="hljs-string"><span class="hljs-string">' errorCode: '</span></span> + errorCode + <span class="hljs-string"><span class="hljs-string">'errorMessage: '</span></span> + errorMessage);

  }
};
<span class="hljs-comment"><span class="hljs-comment">// 设置回调</span></span>
ttsEngine?.setListener(speakListener);

}

//创建对象 private async Creat() { //判断是否支持文本播报 if (!canIUse(‘SystemCapability.AI.TextToSpeech’)) { AlertDialog.show({ message: ‘当前设备不支持文本播报’ }) return Promise.reject(‘当前设备不支持文本播报’) } else {

  <span class="hljs-comment"><span class="hljs-comment">//判断是否存在引擎</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine) {
    <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine
  }

  <span class="hljs-keyword"><span class="hljs-keyword">try</span></span> {

  <span class="hljs-comment"><span class="hljs-comment">//1、创建语音播报对象的设置信息</span></span>
  <span class="hljs-comment"><span class="hljs-comment">/*
   * 配置信息:
   * language :   必填   语种, 当前仅支持“zh-CN”中文。
   * online ;     必填   模式。0为在线,目前不支持;1为离线,当前仅支持离线模式。
   * person ;     必填   音色。0为小艺女生音色,当前仅支持小艺女生音色。
   * extraParams ;可选   附加参数。
   *    &lt;'style', string&gt; 风格。 可选,不设置时默认为“interaction-broadcast”,当前仅支持“interaction-broadcast” 普通话播报。
   *    &lt;'locate', string&gt; 区域信息。可选,不设置时默认为“CN”,当前仅支持“CN”。CN:中国。
   *    &lt;'name', string&gt; 引擎名称。可选,引擎名称,不设置是默认为空。
   * */</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> initParamsInfo: textToSpeech.CreateEngineParams = {
    language: <span class="hljs-string"><span class="hljs-string">'zh-CN'</span></span>,
    person: <span class="hljs-number"><span class="hljs-number">0</span></span>,
    online: <span class="hljs-number"><span class="hljs-number">1</span></span>,
    <span class="hljs-comment"><span class="hljs-comment">// extraParams: { "style": 'interaction-broadcast', "locate": 'CN', "name": 'EngineName' } //name:引擎名称,可自定义</span></span>
  }


  <span class="hljs-comment"><span class="hljs-comment">//1、创建语音播报对象的设置信息</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">const</span></span> ttsEngine = <span class="hljs-keyword"><span class="hljs-keyword">await</span></span> textToSpeech.createEngine(initParamsInfo)

  <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.ttsEngine = ttsEngine

  <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> ttsEngine

  } <span class="hljs-keyword"><span class="hljs-keyword">catch</span></span> (err) {
    <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> Promise.reject(err)
  }

}

} }

export const textTospeech = new TextToSpeech();<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

import { textTospeech } from ‘./TextToSpeech’

@Entry @Component struct Index { @State text:string = ‘你好世界。窗前明月光,疑是地上霜。举头望明月,低头思故乡。您当前正在浏览HarmonyOS NEXT Developer Preview2版本的配套文档’ build() { Column({space:10}){ TextArea({text:$$this.text}) .width(‘80%’)

  Button(<span class="hljs-string"><span class="hljs-string">'文本转语音'</span></span>)
    .onClick<span class="hljs-function"><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(()=&gt;{
      </span></span><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-params"><span class="hljs-keyword">try</span></span></span></span><span class="hljs-function"><span class="hljs-params"> {
        textTospeech.speak(</span></span><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-params"><span class="hljs-keyword">this</span></span></span></span><span class="hljs-function"><span class="hljs-params">.text)
      } </span></span><span class="hljs-keyword"><span class="hljs-function"><span class="hljs-params"><span class="hljs-keyword">catch</span></span></span></span><span class="hljs-function"><span class="hljs-params"> (err) {
        AlertDialog.show({ message: JSON.stringify( err,</span></span><span class="hljs-literal"><span class="hljs-function"><span class="hljs-params"><span class="hljs-literal">null</span></span></span></span><span class="hljs-function"><span class="hljs-params">,</span></span><span class="hljs-number"><span class="hljs-function"><span class="hljs-params"><span class="hljs-number">2</span></span></span></span><span class="hljs-function"><span class="hljs-params">)})
      }
    })</span></span></span><span class="hljs-function">

  </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">Button</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(</span></span><span class="hljs-string"><span class="hljs-function"><span class="hljs-params"><span class="hljs-string">'停止播报'</span></span></span></span><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function">
  .</span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">onClick</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(()=&gt;{
    textTospeech.stop()
  })</span></span></span><span class="hljs-function">

  </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">Button</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(</span></span><span class="hljs-string"><span class="hljs-function"><span class="hljs-params"><span class="hljs-string">'查询支持的音色信息'</span></span></span></span><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function">
    .</span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">onClick</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(async ()=&gt;{
      </span></span><span class="hljs-reserved"><span class="hljs-function"><span class="hljs-params"><span class="hljs-reserved">const</span></span></span></span><span class="hljs-function"><span class="hljs-params"> list =  await textTospeech.GetVoicesList()
      AlertDialog.show({ message: JSON.stringify( list,</span></span><span class="hljs-literal"><span class="hljs-function"><span class="hljs-params"><span class="hljs-literal">null</span></span></span></span><span class="hljs-function"><span class="hljs-params">,</span></span><span class="hljs-number"><span class="hljs-function"><span class="hljs-params"><span class="hljs-number">2</span></span></span></span><span class="hljs-function"><span class="hljs-params">)})
    })</span></span></span><span class="hljs-function">

  </span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">Button</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(</span></span><span class="hljs-string"><span class="hljs-function"><span class="hljs-params"><span class="hljs-string">'查询播报状态'</span></span></span></span><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function">
    .</span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">onClick</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(async ()=&gt;{
      </span></span><span class="hljs-regexp"><span class="hljs-function"><span class="hljs-params"><span class="hljs-regexp">//</span></span></span></span><span class="hljs-function"><span class="hljs-params"> 查询播报状态
      </span></span><span class="hljs-reserved"><span class="hljs-function"><span class="hljs-params"><span class="hljs-reserved">let</span></span></span></span><span class="hljs-function"><span class="hljs-params"> isBusy = await textTospeech.isBusy();
      AlertDialog.show({ message:  JSON.stringify( isBusy,</span></span><span class="hljs-literal"><span class="hljs-function"><span class="hljs-params"><span class="hljs-literal">null</span></span></span></span><span class="hljs-function"><span class="hljs-params">,</span></span><span class="hljs-number"><span class="hljs-function"><span class="hljs-params"><span class="hljs-number">2</span></span></span></span><span class="hljs-function"><span class="hljs-params">)})
    })</span></span></span><span class="hljs-function">
}
.</span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">width</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(</span></span><span class="hljs-string"><span class="hljs-function"><span class="hljs-params"><span class="hljs-string">'100%'</span></span></span></span><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function">
.</span><span class="hljs-title"><span class="hljs-function"><span class="hljs-title">height</span></span></span><span class="hljs-params"><span class="hljs-function"><span class="hljs-params">(</span></span><span class="hljs-string"><span class="hljs-function"><span class="hljs-params"><span class="hljs-string">'100%'</span></span></span></span><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function">

} }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

判断当前是否处于合成或播报中

cke_5443.pngcke_6109.png

查询支持的音色信息

cke_10375.png

2 回复
贴主,有遇到一个问题,如果传入的是1个或者2个汉字,语音播报不生效

HarmonyOS 鸿蒙的Next文本转语音功能通常依赖于系统的TTS(Text-To-Speech)引擎。确保该功能正常工作,首先检查系统更新,确保鸿蒙系统为最新版本,因为新版本可能修复了旧版本的已知问题。其次,检查应用权限设置,确保应用有权限访问麦克风进行语音输出。如果使用的是第三方应用,尝试清除应用缓存或重新安装应用。此外,检查系统设置中的辅助功能或语音设置,确保没有禁用相关服务。如果问题依旧没法解决请加我微信,我的微信是itying888。

回到顶部