在uniapp开发的安卓app中不联网实现语音转文字

需要先说明的是,当前方案是为了解决在安卓app不联网的情况下语音识别转文字;如果没有强制要求完全可以使用现有的识别接口;且当前方案是根据现有插件整合

1.首先需要安装所需插件

根据文档安装和配置以上插件,下面示例是语音识别插件在main.js文件的配置

// 语音识别插件安装之后在的配置
let speechRecModule = null
try {
    speechRecModule = uni.requireNativePlugin('Xyjk-Speech-Recognition')
    speechRecModule.initModel(()=>{
        console.log('语音识别模型初始化完成');
    })
} catch (e) {
    // err
}

Vue.prototype.$speechRecModule = speechRecModule
2.其次要把两个插件配合使用

首先在页面中引入和使用录音动画组件

<template>
    <view>
        <nb-voice-record
            @startRecord="start"
            @endRecord="end"
            @cancelRecord="cancel"
            :btnStyle="btnStyle"
            :btnHoverBgcolor="btnHoverBgcolor"
            btnDefaultText="按住说话"
            btnRecordingText="松开发送 上划取消"
            popupTitle="识别中"
            popupDefaultTips="松开发送"
            popupCancelTips="上划取消"
            :popupMaxWidth="300"
            :recordOptions="recordOptions"
        >
        </nb-voice-record>
    </view>
</template>

然后在页面中触发语音识别组件

<template>
    <view>
        <nb-voice-record
            @startRecord="start"
            @endRecord="end"
            @cancelRecord="cancel"
            :btnStyle="btnStyle"
            :btnHoverBgcolor="btnHoverBgcolor"
            btnDefaultText="按住说话"
            btnRecordingText="松开发送 上划取消"
            popupTitle="识别中"
            popupDefaultTips="松开发送"
            popupCancelTips="上划取消"
            :popupMaxWidth="300"
            :recordOptions="recordOptions"
        >
        </nb-voice-record>
    </view>
</template>
<script>
export default {
    methods: {
        // 开始录音
        start() {
            this.$speechRecModule.startRecord({uniCode: 'speechTest'}, (res)=> {
                console.log('xcx res: ', res)
                if(res.resp_code == 200 && res.speech_text != '') {
                    // res.speech_text是录音转文字之后的数据
                    // some code
                } else {
                    uni.showToast({
                        title: '识别失败',
                        icon: 'none'
                    })
                }
            })
        },
        // 结束录音
        end(event) {
            this.$speechRecModule.stopRecord((e)=>{
                // some code
            })
        },
        // 取消录音
        cancel() {
          this.$speechRecModule.stopRecord((e)=>{
              // some code
          })
        }
    }
}
</script>
3.总结

以上就是根据现有已知的插件组合实现的方案;再次需要强调的是这个仅仅是针对的是不联网安卓app

4.在有网情况下使用百度语音识别api的实现方案

首先需要有相关账号,申请相关服务。

  • 第一步需要配置录音权限
    具体配置路径:manifest.json-->App模块配置--->record(录音),找打之后选中就可以了。
  • 第二部拿到录音文件
    这个可根据具体业务情况来实现,下面是个简单例子
<template>
    <view>
        <nb-voice-record
            @startRecord="start"
            @endRecord="end"
            @cancelRecord="cancel"
            :btnStyle="btnStyle"
            :btnHoverBgcolor="btnHoverBgcolor"
            btnDefaultText="按住说话"
            btnRecordingText="松开发送 上划取消"
            popupTitle="识别中"
            popupDefaultTips="松开发送"
            popupCancelTips="上划取消"
            :popupMaxWidth="300"
            :recordOptions="recordOptions"
        >
        </nb-voice-record>
    </view>
</template>
<script>
export default {
    methods: {
        // 结束录音
        end(event) {
            this.$speechRecModule.stopRecord((e)=>{
                // 拿到录音文件
                const path = event.tempFilePath;
            })
        }
    }
}
</script>
  • 第三部实现百度接口所需要的录音文件转base64方法实现
<script>
export default {
    methods: {
        convertAudioToBase64(filePath, callback) {
            plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
                entry.file(function(file) {
                    var reader = new plus.io.FileReader();
                    reader.onloadend = function(e) {
                        const base64Data = e.target.result
                        const len = file.size
                        
                        callback(base64Data, len);
                    };
                    reader.readAsDataURL(file);
                }, function(e) {
                    console.log("读取文件失败:" + e.message);
                });
            }, function(e) {
                console.log("获取文件对象失败:" + e.message);
            });
        }
    }
}
</script>
  • 第四步提交百度语音识别
<script>
export default {
    methods: {
        async fetchKey(voiceData, dataLen) {
            await ajax.post('http://vop.baidu.com/server_api', {
                format:"pcm",
                rate: 16000,
                channel: 1,
                token: '你的token',
                cuid: '你的id',
                len: dataLen, // 录音文件长度大小
                speech: voiceData, // 录音文件
            }, {}, 9000, true).then(res => {
                console.log('res', res)
                if (_.hasIn(res, 'err_no') && res.err_no === 0 && _.isArray(res.result) && res.result[0] !== '') {
                    
                    // 拿到结果 = res.result[0]
                    // some code
                } else {
                    uni.showToast({
                        title: '识别失败',
                        icon: 'none'
                    })
                }
            }).catch(err => {
                console.log('err', err)
                uni.showToast({
                    title: '识别失败',
                    icon: 'none'
                })
            })
        }
    }
}
</script>
  • 第五步实现从拿到文件到发送的结合
<script>
export default {
    methods: {
        // 结束录音
        end(event) {
            this.$speechRecModule.stopRecord((e)=>{
                // 拿到录音文件
                const path = event.tempFilePath;
                this.convertAudioToBase64(path, (data, len) => {
                    const idx =  data.indexOf('data:audio/vnd.wave;base64,')
                    
                    this.fetchKey(data.replace('data:audio/vnd.wave;base64,', ''), len)
                 })
            })
        }
    }
}
</script>

以上就是调用baidu语音识别转文字的全过程了,希望对您有所帮助。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容