最近想在手机端增加语音识别功能,引用的是百度语音识别api,根据hbuilderx的相关设置
uni-app官网按照官方网站设置-自定义语音识别界面怎么都不生效,找了好多论坛博客才知道
<template>
<view class="content">
<textarea class="result" placeholder="语音识别内容" :value="result"></textarea>
<view class="recogniz">
<view style="color: #0000cc;">
<text>{{title}}</text>
</view>
<view class="partial">
<text>{{partialresult}}</text>
</view>
<view class="volume" :style="{width:valuewidth}"></view>
</view>
<button type="default" @touchstart="startrecognize" @touchend="endrecognize">按下开始&松开结束</button>
</view>
</template>
<script>
export default {
data() {
return {
title: '未开始',
text: '',
partialresult: '...',
result: '',
valuewidth: '0px'
}
},
onload() {
// #ifdef app-plus
// 监听语音识别事件
plus.speech.addeventlistener('start', this.ontstart, false);
plus.speech.addeventlistener('volumechange', this.onvolumechange, false);
plus.speech.addeventlistener('recognizing', this.onrecognizing, false);
plus.speech.addeventlistener('recognition', this.onrecognition, false);
plus.speech.addeventlistener('end', this.onend, false);
// #endif
},
methods: {
ontstart() {
this.title = '...倾听中...';
this.text = '';
console.log('event: start');
},
onvolumechange(e) {
this.valuewidth = 100*e.volume+'px';
console.log('event: volumechange '+this.valuewidth);
},
onrecognizing(e) {
this.partialresult = e.partialresult;
console.log('event: recognizing');
},
onrecognition(e) {
this.text += e.result;
this.text?(this.text+='\n'):this.text='';
this.result = this.text;
this.partialresult = e.result;
console.log('event: recognition');
},
onend() {
if(!this.text||this.text==''){
plus.nativeui.toast('没有识别到内容');
}
this.result = this.text;
this.title = '未开始';
this.valuewidth = '0px';
this.partialresult = '...';
},
startrecognize() {
console.log('startrecognize');
// #ifdef app-plus
plus.speech.startrecognize({
engine: 'baidu',
lang: 'zh-cn',
'userinterface': false,
'continue': true
});
// #endif
},
endrecognize() {
console.log('endrecognize');
// #ifdef app-plus
plus.speech.stoprecognize();
// #endif
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.recogniz {
width: 200px;
height: 100px;
padding: 12px;
margin: 50px auto;
background-color: rgba(0,0,0,0.5);
border-radius: 16px;
text-align: center;
}
.partial {
width: 100%;
height: 40px;
margin-top: 16px;
font-size: 12px;
color: #ffffff;
}
.volume {
width: 10px;
height: 6px;
border-style:solid;
display:inline-block;
box-sizing:border-box;
border-width:1px;
border-color:#cccccc;
border-radius: 50%;
background-color: #00cc00;
}
.result {
color: #cccccc;
border: #00cccc 1px solid;
margin: 25px auto;
padding: 6px;
width: 80%;
height: 100px;
}
</style>
以上代码中 识别语音中参数userinterface设置为true才能生效,天坑。
发表评论