效果如下,可能有点丑,但功能齐全…
NPM
npm install recorderx --sava
页面引用
import axios from 'axios'
import Recorderx, { ENCODE_TYPE } from "recorderx";
const rc = new Recorderx();
样式
<!-- 语音 -->
<i class="el-icon-microphone" @click = 'handleBtnClick' ></i>
<!-- <audio controls autoplay id="audio"></audio> -->
<ButtonGroup size='small' v-show = "news_img">
<!-- <Button @click="play_mp3">播放</Button> -->
<Button @click="send_voice">发送</Button>
<Button @click="cancel_mp3">停止</Button>
<!-- <Button @click="cancel">取消</Button> -->
</ButtonGroup>
功能
methods: {
//录制语音
handleBtnClick: function () {
let that = this
// that.news_img = !that.news_img
rc.start()
.then(() => {
that.news_img = !that.news_img
console.log("start recording");
})
.catch(error => {
alert('获取麦克风失败')
console.log("Recording failed.", error);
});
},
//暂停语音
cancel_mp3: function() {
rc.pause();
},
//取消语音
// cancel: function() {
// rc.clear();
// },
//播放语音
// play_mp3:function(){
// var wav = rc.getRecord({
// encodeTo: ENCODE_TYPE.WAV,
// compressible: true
// });
// document.getElementById('audio').src = URL.createObjectURL(wav);
// },
//发送语音
send_voice: function () {
let that = this
var wav = rc.getRecord({
encodeTo: ENCODE_TYPE.WAV,
compressible: true
});
var uuid = this.uuid;
if (this.chatList != "") {
var end_time = this.chatList[this.chatList.length - 1].addtime;
}
var formData = new FormData();
// formData.append('file',wav);
formData.append('topic_id',uuid);
formData.append('last_time',end_time);
formData.append('type',4);
formData.append("file", wav,Date.parse(new Date())+".wav");
let headers = {headers: {"Content-Type": "multipart/form-data"}}
axios.defaults.withCredentials=true
axios.post( this.https + "/admin/api/send_reply",formData,headers).then(data => {
that.news_img = !that.news_img
// this.reload();
rc.clear();
})
.catch(err => {
console.log(err);
});
// this.$request({
// url: "/api/send_reply",
// method: "post",
// data:formData,
// headers: {"Content-Type": "multipart/form-data"}
// }).then(data => {
// that.news_img = !that.news_img
// this.content = "";
// })
// .catch(err => {
// console.log(err);
// });
},
}
注释
rc.start();//录音
rc.pause();//暂停录音
rc.clear();//清除录音缓存
更多用法见大佬GitHub