一、介绍
基于鸿蒙Next模拟一个输入用户文字,转化成语音播报效果
二、场景需求
辅助功能:为视障人士提供帮助:将文字内容转化为语音,使视觉障碍用户能够获取信息。
教育与学习:语言学习:帮助学习者通过听力学习语言,提供正确的发音。
有声读物:将电子书或教材转化为有声形式,方便学习和阅读。
客户服务:自动语音应答系统:在客户服务热线中,通过语音播报来解答常见问题或提供信息。
智能设备:智能家居助手:例如,Google Assistant、Amazon Alexa等通过语音播报来提供天气、提醒事项等信息。
导航与交通:GPS导航:将路线信息和交通提示转化为语音,提高驾驶安全性和便利性。
新闻与信息播报:语音助手:用户可以听取最新新闻、天气预报等信息,实现信息的快速获取等等。
三、业务步骤
第一步:输入框输入想转化的文字
第二部:文字转化成语音播报出来
四、效果展示
五:代码展示:
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 = {"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 = {"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)
}
}