欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 输入文字转化语音

输入文字转化语音

2025/4/19 9:28:47 来源:https://blog.csdn.net/weixin_69135651/article/details/141635376  浏览:    关键词:输入文字转化语音

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

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

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

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

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

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

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

#HarmonyOS NEXT 体验官#输入文字转化语音-鸿蒙开发者社区


五:代码展示:

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.isPlayif (this.isPlay == true){let val:string = this.inputValuethis.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.isPlayif (this.isPlay == true){let val:string = this.inputValuethis.createByCallback()this.listVoicesCallback(this.inputValueIdx.toString())this.speak(val,this.inputValueIdx.toString())}else {ttsEngine.shutdown()}})}.width("100%").height("100%").justifyContent(FlexAlign.Center).backgroundColor(0xfadf99)}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词