HarmonyOS 鸿蒙Next输入文字转化语音
HarmonyOS 鸿蒙Next输入文字转化语音
一、介绍
基于鸿蒙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<string, Object> = {“style”: ‘interaction-broadcast’, “locate”: ‘CN’, “name”: ‘EngineName’};
let initParamsInfo: textToSpeech.CreateEngineParams = {
language: ‘zh-CN’,
person: 0,
online: 1,
extraParams: extraParam
};
<span class="hljs-comment"><span class="hljs-comment">// 调用createEngine方法</span></span>
textToSpeech.createEngine(initParamsInfo, (err: BusinessError, textToSpeechEngine: textToSpeech.TextToSpeechEngine) => {
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (!err) {
console.info(<span class="hljs-string"><span class="hljs-string">'Succeeded in creating engine.'</span></span>);
<span class="hljs-comment"><span class="hljs-comment">// 接收创建引擎的实例</span></span>
ttsEngine = textToSpeechEngine;
} <span class="hljs-keyword"><span class="hljs-keyword">else</span></span> {
<span class="hljs-comment"><span class="hljs-comment">// 创建引擎失败时返回错误码1003400005,可能原因:引擎不存在、资源不存在、创建引擎超时</span></span>
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: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(response)}
);
},
// 完成播报回调
onComplete(requestId: string, response: textToSpeech.CompleteResponse) {
console.info(onComplete, requestId: ${requestId} response: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(response)}
);
},
// 停止播报完成回调,调用stop方法并完成时会触发此回调
onStop(requestId: string, response: textToSpeech.StopResponse) {
console.info(onStop, requestId: ${requestId} response: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(response)}
);
},
// 返回音频流
onData(requestId: string, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) {
console.info(onData, requestId: ${requestId} sequence: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(response)} audio: ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.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
};
<span class="hljs-comment"><span class="hljs-comment">// 调用listVoices方法,以callback返回语种音色查询结果</span></span>
ttsEngine.listVoices(voicesQuery, (err: BusinessError, voiceInfo: textToSpeech.VoiceInfo[]) => {
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (!err) {
<span class="hljs-comment"><span class="hljs-comment">// 接收目前支持的语种音色等信息</span></span>
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.voiceInfo = <span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(voiceInfo);
console.info(`Succeeded <span class="hljs-keyword"><span class="hljs-keyword">in</span></span> listing voices, voiceInfo is ${voiceInfo}`);
} <span class="hljs-keyword"><span class="hljs-keyword">else</span></span> {
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(<span class="hljs-string"><span class="hljs-string">'app.media.idiom_yuyin'</span></span>)).width(<span class="hljs-number"><span class="hljs-number">44</span></span>).height(<span class="hljs-number"><span class="hljs-number">44</span></span>)
.onClick(()=>{
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay = !<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay == <span class="hljs-literal"><span class="hljs-literal">true</span></span>){
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> val:string = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.createByCallback()
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.listVoicesCallback(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx.toString())
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.speak(val,<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx.toString())
}<span class="hljs-keyword"><span class="hljs-keyword">else</span></span> {
ttsEngine.shutdown()
}
})
}.width(<span class="hljs-number"><span class="hljs-number">70</span></span>)
.height(<span class="hljs-number"><span class="hljs-number">70</span></span>)
.borderWidth(<span class="hljs-number"><span class="hljs-number">2</span></span>)
.borderColor(<span class="hljs-number"><span class="hljs-number">0xFFFFFF</span></span>)
.borderRadius(<span class="hljs-number"><span class="hljs-number">35</span></span>)
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.stateStyles({
normal:{.backgroundColor(<span class="hljs-number"><span class="hljs-number">0xF9F3EF</span></span>)},
pressed:{.backgroundColor(<span class="hljs-number"><span class="hljs-number">0xFFEFE5</span></span>)}
})
.onClick(()=>{
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx++
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay = !<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay
<span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isPlay == <span class="hljs-literal"><span class="hljs-literal">true</span></span>){
<span class="hljs-keyword"><span class="hljs-keyword">let</span></span> val:string = <span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValue
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.createByCallback()
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.listVoicesCallback(<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx.toString())
<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.speak(val,<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.inputValueIdx.toString())
}<span class="hljs-keyword"><span class="hljs-keyword">else</span></span> {
ttsEngine.shutdown()
}
})
}.width(<span class="hljs-string"><span class="hljs-string">"100%"</span></span>)
.height(<span class="hljs-string"><span class="hljs-string">"100%"</span></span>)
.justifyContent(FlexAlign.Center)
.backgroundColor(<span class="hljs-number"><span class="hljs-number">0xfadf99</span></span>)
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
关于HarmonyOS 鸿蒙Next输入文字转化语音的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
HarmonyOS的隐私保护机制让我在使用时更加安心,不用担心信息泄露。