科大讯飞官方文档:语音听写(流式版)WebAPI 文档 | 讯飞开放平台文档中心
这是demo
这次主要是将demo改写成了vue语法,其他的都没变。
先在public文件下加入了iat,也就是demo文件中的dist文件夹
然后还要准备CryptoJS这个第三方的包import CryptoJS from ‘crypto-js’;,直接npm下载就行。
最后是封装了一个组件,来使用。这个项目使用的是ant的组件库。可自行换成别的。
<script>
import { Close, Voice } from '@icon-park/vue-next';
import CryptoJS from 'crypto-js';
import { message } from 'ant-design-vue';
export default {
name: 'XfIat',
components: { Close, Voice },
data() {
return {
// 控制录音弹窗
voiceOpen: false,
// 是否开始录音
startVoiceStatus: false,
// 识别中状态
identifyStatus: false,
recorder: null,
transcription: '',
btnStatus: '',
resultText: '',
resultTextTemp: '',
countdownInterval: null,
iatWS: null,
recognition: null,
};
},
emits: ['sendMsg'],
props: {
buttonDisabled: {
type: Boolean,
default: true,
},
loading: {
type: Boolean,
default: false,
},
xfIatKeys: {
default: {
APPID: '',
APIKey: '',
APISecret: '',
},
},
},
methods: {
/**
* 打开录音
* @returns {Promise<void>}
*/
async startVoice() {
if (this.loading) {
return;
}
this.voiceOpen = true;
await this.playIatVoice();
},
async playIatVoice() {
if (this.loading) {
return;
}
this.startVoiceStatus = !this.startVoiceStatus;
// 浏览器自带的识别
if (this.recognition) {
if (this.startVoiceStatus) {
this.recognition.start();
} else {
this.recognition.stop();
}
return;
}
if (this.startVoiceStatus) {
this.connectWebSocket();
} else {
this.recorder.stop();
}
},
/**
* 关闭录音弹窗
*/
closeVoiceOpen() {
this.voiceOpen = false;
this.startVoiceStatus = false;
if (this.recorder) {
this.recorder.stop();
}
if (this.recognition) {
this.recognition.stop();
}
this.transcription = '';
},
renderResult(resultData) {
// 识别结束
const jsonData = JSON.parse(resultData);
if (jsonData.data && jsonData.data.result) {
const data = jsonData.data.result;
let str = '';
const { ws } = data;
for (let i = 0; i < ws.length; i += 1) {
str += ws[i].cw[0].w;
}
// 开启wpgs会有此字段(前提:在控制台开通动态修正功能)
// 取值为 "apd"时表示该片结果是追加到前面的最终结果;取值为"rpl" 时表示替换前面的部分结果,替换范围为rg字段
if (data.pgs) {
if (data.pgs === 'apd') {
// 将resultTextTemp同步给resultText
this.resultText = this.resultTextTemp;
}
// 将结果存储在resultTextTemp中
this.resultTextTemp = this.resultText + str;
} else {
this.resultText += str;
}
this.transcription = this.resultTextTemp || this.resultText || '';
}