<template>
<div>
<div>
<button @click="startRecording">开始录音</button>
<button @click="stopRecording">停止录音</button>
<button @click="bofang">播放</button>
<audio ref="audioPlayer"></audio>
</div>
</div>
</template>
<script>
// import lamejs from 'lamejs';
import * as qiniu from "qiniu-js";
import axios from "axios";
export default {
data() {
return {
isRecording: false,
stream: null,
recorder: null,
chunks: [],
audioUrl: null,
num: 0,
timer: 'null',
blob: null,
};
},
beforeDestroy() {
// 组件销毁前释放资源
if (this.audioUrl) {
URL.revokeObjectURL(this.audioUrl);
}
},
methods: {
async startRecording() {
if (this.isRecording) {
return; // 已经在录音了,不需要再次开始
}
this.timer = setInterval(() => {
this.num++
}, 1000)
this.chunks = []
this.isRecording = true;
this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.recorder = new MediaRecorder(this.stream);
this.recorder.addEventListener('dataavailable', event => {
console.log(event, 'event');
this.chunks.push(event.data);
this.blob = new Blob(this.chunks, { type: 'audio/mp3' });
});
this.recorder.start();
},
stopRecording() {
if (!this.isRecording) {
alert('没有在录音,不需要停止')
return; // 没有在录音,不需要停止
}
clearInterval(this.timer)
this.isRecording = false;
this.recorder.stop();
this.stream.getTracks().forEach(track => track.stop());
// 将录制的音频数据转换为Blob对象
// let localUrl = (window.URL || window.webkitURL).createObjectURL(this.blob)
// localUrl = localUrl.substr(27)
console.log(this.blob, 888);
// console.log(localUrl, 8888);
console.log(this.chunks);
console.log(URL.createObjectURL(this.blob));
// if (this.audioUrl) {
// URL.revokeObjectURL(this.audioUrl);
// }
// 使用七牛云SDK进行文件上传
axios.get('*********************').then(res => {
const token = res.data.Result.UploadToken;
const key = 'vvchat.app/' + new Date().getTime(); // 上传后在七牛云上的文件名
const config = {
useCdnDomain: true,
region: qiniu.region.as0
};
const putExtra = {
mimeType: 'audio/mp3'
};
const observable = qiniu.upload(this.blob, key, token, putExtra, config);
observable.subscribe({
next(res) {
// 上传进度回调
console.log('上传进度:', res.total.percent);
},
error(err) {
// 上传失败回调
console.error('上传失败:', err);
},
complete(res) {
// 上传完成回调
console.log('上传成功:', res);
}
});
})
},
bofang() {
this.$refs.audioPlayer.src = URL.createObjectURL(this.blob);
this.$refs.audioPlayer.play();
}
}
};
</script>
vue录音实现
发布于 2024-08-08 143 次阅读
Comments NOTHING