uniapp录音功能代码
时间: 2023-08-27 08:05:13 浏览: 48
以下是一份使用uniapp录音功能的示例代码:
```vue
<template>
<view class="container">
<view class="record-btn" @touchstart="startRecord" @touchend="stopRecord">
<view class="record-icon"></view>
<view class="record-text">按住录音</view>
</view>
<audio :src="audioSrc" controls></audio>
</view>
</template>
<script>
export default {
data() {
return {
audioSrc: '',
recorderManager: null,
isRecording: false
}
},
mounted() {
this.recorderManager = uni.getRecorderManager()
// 设置录音参数
this.recorderManager.onStart(() => {
console.log('recorder start')
})
this.recorderManager.onStop((res) => {
console.log('recorder stop', res)
this.audioSrc = res.tempFilePath
this.isRecording = false
})
this.recorderManager.onFrameRecorded((res) => {
console.log('frameBuffer length', res.frameBuffer.length)
})
this.recorderManager.onError((res) => {
console.log('recorder error', res)
})
},
methods: {
startRecord() {
if (this.isRecording) {
return
}
// 开始录音
this.isRecording = true
this.recorderManager.start({
format: 'mp3'
})
},
stopRecord() {
if (!this.isRecording) {
return
}
// 结束录音
this.isRecording = false
this.recorderManager.stop()
}
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.record-btn {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 120px;
height: 120px;
border-radius: 50%;
background-color: red;
}
.record-btn:active {
background-color: darkred;
}
.record-icon {
width: 60px;
height: 60px;
border-radius: 50%;
background-color: white;
}
.record-text {
margin-top: 10px;
font-size: 14px;
font-weight: bold;
color: white;
}
audio {
margin-top: 20px;
width: 80%;
max-width: 600px;
}
</style>
```
在这个例子中,我们创建了一个包含一个录音按钮和一个播放录音的音频标签的界面。当用户按下录音按钮时,我们通过调用uni的`getRecorderManager`获取一个录音管理器实例。我们设置录音格式为mp3,然后调用`start`方法开始录音。当用户松开按键时,我们调用`stop`方法结束录音。录音结束时,我们会在控制台中输出录音文件的临时路径,并将其设置为音频标签的`src`属性,以便播放录音。在录音过程中,我们还可以通过`onFrameRecorded`事件监听录音帧的数据。在录音出现错误时,我们可以通过`onError`事件进行处理。
这只是一个简单的示例,你可以根据自己的需求进行扩展。要注意的是,录音功能需要用户授权,你需要在`manifest.json`文件中声明录音权限:
```json
{
"permissions": {
"record": {
"desc": "录音功能需要授权"
}
}
}
```