uniapp实现语音识别

前言: 本篇文章主要是调用录音将录音文件传递给后端进行识别

app,微信小程序实现录音功能

使用的api - uni.getRecorderManager()

uni.getRecorderManager() | uni-app官网

api在H5是并不兼容的

按钮

     <!--按钮-->
		<view  class="bottom flex-column">
			<view class="tip flex-column">请按住说话</view>
			<view class="btns flex-row">
				<view @touchstart="startSay" @touchend="endSay" class="button flex-column">
					<text class="iconfont icon-voice"></text>
				</view>
			</view>
		</view>

创建初始化事件和监听录音成功

<script>
// #ifdef MP-WEIXIN
const recorderManager = uni.getRecorderManager();
// #endif

export default{
   data() {
        return {
            voicePath: '', //录音文件
        }
   }
   onLoad() {
		this.interValTime = 100
	    let self = this;
        // #ifdef MP-WEIXIN
		recorderManager.onStop(function (res) {
			self.voicePath = res.tempFilePath;
			self.getData();
		});			
        // #endif
   },
   methods: {
             let token = uni.getStorageasync('token')
             uni.uploadFile({
						url: 'resume/voiceToText',
						name: 'file',
						filePath: this.voicePath,
						header: {
							'Authorization': `bearer ${token}`
						},
						success: (res) => {
							
						},
						fail: (err) => {
						
						}
					})
    }
</script>

开始录音和停止录音

扫描二维码关注公众号,回复: 14949201 查看本文章
           startSay() {
				// #ifdef MP-WEIXIN
				recorderManager.start();
				// #endif
			},
          endSay() {	
				// #ifdef MP-WEIXIN
				recorderManager.stop();
				// #endif
				
			},

H5实现录音功能

uniapp的原生api是不支持h5的,因此h5要进行录音,需要借助插件

插件是通过的,不仅是unipp,其他项目依旧可以使用

npm install recorder-core

使用

   // #ifdef H5
	import Recorder from 'recorder-core'
	import 'recorder-core/src/engine/wav.js'
	// #endif
      data() {
       return {
         rec: null
       }
      },
      onLoad() {
			// #ifdef H5
			this.initRecords()
			// #endif
		},
          initRecords() {
				var rec = this.rec = Recorder({
					type: "wav",
					bitRate: 16,
					sampleRate: 32000,
				});
				rec.open(() => {}, () => {
					uni.showToast({
						title: '获取手机录音权限失败',
						icon: 'none'
					})
				});
			},
          startSay() {
				// #ifdef H5
				if (!this.rec) {
					return;
				}
				this.rec.start();
				// #endif
			},
			endSay() {
				// #ifdef H5
				if (!this.rec) {
					return;
				}
				this.rec.stop((blob, duration) => {
					const file = new File([blob], 'record.wav', {
						type: blob.type
					})
					this.voicePath = file
					this.getData()
				})
				// #endif
			}

getData也是将文件上传给后端

猜你喜欢

转载自blog.csdn.net/qq_42625428/article/details/124323237