【鸿蒙实战开发】HarmonyOS输入文字转化语音实现

10 篇文章 0 订阅
10 篇文章 0 订阅

一、介绍
基于鸿蒙Next模拟一个输入用户文字,转化成语音播报效果
二、场景需求
辅助功能:为视障人士提供帮助:将文字内容转化为语音,使视觉障碍用户能够获取信息。

教育与学习:语言学习:帮助学习者通过听力学习语言,提供正确的发音。
有声读物:将电子书或教材转化为有声形式,方便学习和阅读。

客户服务:自动语音应答系统:在客户服务热线中,通过语音播报来解答常见问题或提供信息。

智能设备:智能家居助手:例如,Google Assistant、Amazon Alexa等通过语音播报来提供天气、提醒事项等信息。

导航与交通:GPS导航:将路线信息和交通提示转化为语音,提高驾驶安全性和便利性。

新闻与信息播报:语音助手:用户可以听取最新新闻、天气预报等信息,实现信息的快速获取等等。

三、业务步骤
第一步:输入框输入想转化的文字
第二部:文字转化成语音播报出来
四、效果展示
image.png

五:代码展示:

mport { textToSpeech } from '@kit.CoreSpeechKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ttsEngine: textToSpeech.TextToSpeechEngine;

@Entry
@Component
struct Index05 {
  @State isPlay: boolean = false //是否播放
  @State voiceInfo: string = ""; //接收目前支持的语种音色等信息
  @State inputValue: string = ""; //输入值
  @State inputValueIdx: number = 0; //
  aboutToAppear() {
    this.createByCallback()
  }

  aboutToDisappear(): void {
    ttsEngine.shutdown()
  }

  // 创建引擎,通过callback形式返回
  // 当引擎不存在、引擎资源不存在、初始化超时,返回错误码1003400005,引擎创建失败
  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 {
        // 创建引擎失败时返回错误码1003400005,可能原因:引擎不存在、资源不存在、创建引擎超时
        console.error(`Failed to create engine. Code: ${err.code}, message: ${err.message}.`);
      }
    });

  };

  // 调用speak播报方法
  // 未初始化引擎时调用speak方法,返回错误码1003400007,合成及播报失败
  private speak(textValue:string,req_ID:string) {
    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: req_ID, // requestId在同一实例内仅能用一次,请勿重复设置
      extraParams: extraParam
    };
    // 调用speak播报方法
    ttsEngine.speak(textValue, speakParams);
  };

  // 查询语种音色信息,以callback形式返回
  private listVoicesCallback(req_ID:string) {
    // 设置查询相关参数
    let voicesQuery: textToSpeech.VoiceQuery = {
      requestId: req_ID, // 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}`);
      }
    });
  };

  build() {
    Column(){
      TextArea({placeholder:'请输入...'})
        .width('80%')
        .onChange((value:string)=>{
          this.inputValue = value
        })
        .margin({bottom:20})
        .backgroundColor(0XFFFFFF)

      Column(){
        Image($r('app.media.idiom_yuyin')).width(44).height(44)
          .onClick(()=>{
            this.isPlay = !this.isPlay
            if (this.isPlay == true){
              let val:string = this.inputValue
              this.createByCallback()
              this.listVoicesCallback(this.inputValueIdx.toString())
              this.speak(val,this.inputValueIdx.toString())
            }else {
              ttsEngine.shutdown()
            }
          })
      }.width(70)
      .height(70)
      .borderWidth(2)
      .borderColor(0xFFFFFF)
      .borderRadius(35)
      .justifyContent(FlexAlign.Center)
      .alignItems(HorizontalAlign.Center)
      .stateStyles({
        normal:{.backgroundColor(0xF9F3EF)},
        pressed:{.backgroundColor(0xFFEFE5)}
      })
      .onClick(()=>{
        this.inputValueIdx = this.inputValueIdx++
        this.isPlay = !this.isPlay
        if (this.isPlay == true){
          let val:string = this.inputValue
          this.createByCallback()

          this.listVoicesCallback(this.inputValueIdx.toString())
          this.speak(val,this.inputValueIdx.toString())
        }else {
          ttsEngine.shutdown()
        }
      })
    }.width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
    .backgroundColor(0xfadf99)
  }
}

写在最后

●如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我两个小忙:
●点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
●关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。

在这里插入图片描述

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值