在uniapp開發(fā)的安卓app中不聯(lián)網(wǎng)實現(xiàn)語音轉(zhuǎn)文字

需要先說明的是,當(dāng)前方案是為了解決在安卓app不聯(lián)網(wǎng)的情況下語音識別轉(zhuǎn)文字;如果沒有強制要求完全可以使用現(xiàn)有的識別接口;且當(dāng)前方案是根據(jù)現(xiàn)有插件整合

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

根據(jù)文檔安裝和配置以上插件,下面示例是語音識別插件在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="松開發(fā)送 上劃取消"
            popupTitle="識別中"
            popupDefaultTips="松開發(fā)送"
            popupCancelTips="上劃取消"
            :popupMaxWidth="300"
            :recordOptions="recordOptions"
        >
        </nb-voice-record>
    </view>
</template>

然后在頁面中觸發(fā)語音識別組件

<template>
    <view>
        <nb-voice-record
            @startRecord="start"
            @endRecord="end"
            @cancelRecord="cancel"
            :btnStyle="btnStyle"
            :btnHoverBgcolor="btnHoverBgcolor"
            btnDefaultText="按住說話"
            btnRecordingText="松開發(fā)送 上劃取消"
            popupTitle="識別中"
            popupDefaultTips="松開發(fā)送"
            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是錄音轉(zhuǎn)文字之后的數(shù)據(jù)
                    // some code
                } else {
                    uni.showToast({
                        title: '識別失敗',
                        icon: 'none'
                    })
                }
            })
        },
        // 結(jié)束錄音
        end(event) {
            this.$speechRecModule.stopRecord((e)=>{
                // some code
            })
        },
        // 取消錄音
        cancel() {
          this.$speechRecModule.stopRecord((e)=>{
              // some code
          })
        }
    }
}
</script>
3.總結(jié)

以上就是根據(jù)現(xiàn)有已知的插件組合實現(xiàn)的方案;再次需要強調(diào)的是這個僅僅是針對的是不聯(lián)網(wǎng)安卓app。

4.在有網(wǎng)情況下使用百度語音識別api的實現(xiàn)方案

首先需要有相關(guān)賬號,申請相關(guān)服務(wù)。

  • 第一步需要配置錄音權(quán)限
    具體配置路徑:manifest.json-->App模塊配置--->record(錄音),找打之后選中就可以了。
  • 第二部拿到錄音文件
    這個可根據(jù)具體業(yè)務(wù)情況來實現(xiàn),下面是個簡單例子
<template>
    <view>
        <nb-voice-record
            @startRecord="start"
            @endRecord="end"
            @cancelRecord="cancel"
            :btnStyle="btnStyle"
            :btnHoverBgcolor="btnHoverBgcolor"
            btnDefaultText="按住說話"
            btnRecordingText="松開發(fā)送 上劃取消"
            popupTitle="識別中"
            popupDefaultTips="松開發(fā)送"
            popupCancelTips="上劃取消"
            :popupMaxWidth="300"
            :recordOptions="recordOptions"
        >
        </nb-voice-record>
    </view>
</template>
<script>
export default {
    methods: {
        // 結(jié)束錄音
        end(event) {
            this.$speechRecModule.stopRecord((e)=>{
                // 拿到錄音文件
                const path = event.tempFilePath;
            })
        }
    }
}
</script>
  • 第三部實現(xiàn)百度接口所需要的錄音文件轉(zhuǎn)base64方法實現(xiàn)
<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] !== '') {
                    
                    // 拿到結(jié)果 = res.result[0]
                    // some code
                } else {
                    uni.showToast({
                        title: '識別失敗',
                        icon: 'none'
                    })
                }
            }).catch(err => {
                console.log('err', err)
                uni.showToast({
                    title: '識別失敗',
                    icon: 'none'
                })
            })
        }
    }
}
</script>
  • 第五步實現(xiàn)從拿到文件到發(fā)送的結(jié)合
<script>
export default {
    methods: {
        // 結(jié)束錄音
        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>

以上就是調(diào)用baidu語音識別轉(zhuǎn)文字的全過程了,希望對您有所幫助。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容