js-audio-recorder语音录制 H5开发内嵌在微信小程序
按住按钮录音
松开按钮上传录音,代码里有两个时间一个是按住按钮的时间,一个是录音时间,在手机上还是用录音时间适配比较好。代码在下面
使用
1.安装js-audio-recorder
npm i js-audio-recorder
demo文件,复制拿去就能用,样式可以自己调试
<template>
<div
v-loading="loading"
element-loading-text="正在获取麦克风设备"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)"
class="voice-recorder">
<button
class="record-button"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
:class="{ 'is-recording': isRecording }"
>
{{ isRecording ? '松开结束\n' + recorder.duration.toFixed(4) : '按住说话' }}
<!-- 这里可以添加一个额外的元素来显示波形图或更多信息,但这里只显示了时间 -->
<div v-if="isRecording" class="recording-indicator">
<!-- <span>{{ formattedRecordTime }}</span> -->
<!-- <span>{{ recorder.duration.toFixed(4) }}</span> -->
</div>
</button>
</div>
</template>
<script>
import Recorder from 'js-audio-recorder'
export default {
data() {
return {
loading:false,
isRecording: false,
recordStartTime: null,
recordTime: 0,
recorder: null,
playTime: 0,
timer: null,
src: null
};
},
computed: {
formattedRecordTime() {
// 简单的格式化录音时间,这里只显示秒数
return Math.floor(this.recordTime) + 's';
// 如果需要更详细的格式(如分:秒),可以相应地调整
},
},
mounted(){
this.getvideo()
},
methods: {
getvideo(){
this.loading=true
this.recorder = new Recorder({
sampleBits: 16, // 采样位数,支持 8 或 16,默认是 16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,Chrome 是 48000
numChannels: 1, // 声道数,支持 1 或 2, 默认是 1
}),
Recorder.getPermission().then(() => {
this.loading=false
this.recorder.start() // 开始录音
}, (error) => {
this.loading=false
this.$message({
message: '请先允许该网页使用麦克风',
type: 'info'
})
console.log(`${error.name} : ${error.message}`)
},
)
},
//按钮按住事件
handleTouchStart() {
this.isRecording = true;
this.recordStartTime = Date.now();
this.updateRecordTime();
console.log(333,this.recorder)
this.recorder = new Recorder({
sampleBits: 16, // 采样位数,支持 8 或 16,默认是 16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,Chrome 是 48000
numChannels: 1, // 声道数,支持 1 或 2, 默认是 1
}),
Recorder.getPermission().then(() => {
console.log("执行开始录音",this.recorder,this.recorder.duration)
this.$toast('开始录音');
this.recorder.start() // 开始录音
}, (error) => {
this.$message({
message: '请先允许该网页使用麦克风',
type: 'info'
})
console.log(`${error.name} : ${error.message}`)
})
},
//按钮松开事件
handleTouchEnd() {
this.isRecording = false;
// 停止更新录音时间
clearInterval(this.recordTimeInterval);
// 这里可以添加停止录音和处理录音文件的逻辑
if (this.recorder == null || this.recorder.duration === 0) {
this.$message({
message: '请先录音',
type: 'error'
})
this.recorder.stop() // 暂停录音
this.timer = null
return false
}
this.recorder.stop() // 暂停录音
this.timer = null
// const blob = this.recorder.getPCMBlob() // 获取 pcm 格式音频数据
const blob = this.recorder.getWAVBlob() // 获取 pcm 格式音频数据
const newBlob = new Blob([blob])
// 此处获取到 blob 对象后需要设置 fileName 满足项目上传需求,这里选择把 blob 包装成 file 塞入 formData
const fileOfBlob = new File([newBlob], new Date().getTime() + '.wav')
const formData = new FormData()
formData.append('file', fileOfBlob)
const url = window.URL.createObjectURL(fileOfBlob)
this.src = url
this.$axios.post('后端上传地址', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res)
this.$emit('addNum',res)//上传成功回显到父组件
})
},
updateRecordTime() {
this.recordTimeInterval = setInterval(() => {
if (this.isRecording) {
this.recordTime = (Date.now() - this.recordStartTime) / 1000;
}
}, 100); // 每100毫秒更新一次录音时间
},
},
beforeDestroy() {
// 确保在组件销毁前清除定时器
if (this.recordTimeInterval) {
clearInterval(this.recordTimeInterval);
}
},
};
</script>
<style scoped>
.record-button {
width: 100%;
/* height: 100%; */
height: 50px;
/* border-radius: 50%; */
/* padding: 10px 20px; */
color: white;
font-size: 14px;
background-color: #007bff;
border: none;
cursor: pointer;
/* position: relative; */
overflow: hidden; /* 确保录音时间不会溢出按钮 */
white-space: pre-wrap; /* 允许文本换行 */
/* border: 1px solid red; */
}
.record-button.is-recording {
background-color: #dc3545; /* 录音时改变背景颜色 */
}
.recording-indicator {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
color: white;
text-align: center;
/* 根据需要调整其他样式 */
}
</style>
下面单独添加一块CSS代码 是运行在手机各个浏览器上防止长按复制 给用户的体验感更流畅
* {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
user-select: none; /* Likely future */
-webkit-touch-callout: none; /* iOS Safari */
}