本篇文章给大家分享的是有关怎么在Vue中利用node实现音频录制播放功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
vue部分:
安装recorderx
cnpm install recorderx --save
或者
npm install recorderx --save
在具体的组件中引入
<script>
import axios from "axios";
import {
Toast
} from "vant";
import Recorderx, {
ENCODE_TYPE
} from "recorderx";
const rc = new Recorderx();
export default {
data(){
return{
startime:null,
endtime :null
}
},
methods:{
//录制语音
recordingVoice() {
// that.news_img = !that.news_img
rc.start()
.then(() => {
this.startime = new Date();
})
.catch(error => {
alert("获取麦克风失败");
});
},
//发送语音
async sendVoice() {
rc.pause();
this.endtime = new Date();
let wav = rc.getRecord({
encodeTo: ENCODE_TYPE.WAV,
compressible: true
});
let voiceTime = Math.ceil((this.endtime - this.startime) / 1000);
const formData = new FormData();
formData.append("chatVoice", wav, Date.parse(new Date()) + ".wav");
formData.append("voiceTime", voiceTime);
let headers = {
headers: {
"Content-Type": "multipart/form-data"
}
};
axios
.post("/api/uploadChatVoice", formData, headers)
.then(res => {
//console.log(res)
if (res.data.status === 2) {
rc.clear();
let chatVoiceMsg = res.data.chatVoiceMsg;
}
}
});
},
//播放语音
playChatVoice(audio) {
let audioUrl = audio;
if(audioUrl){
let audioExample = new Audio();
audioExample.src = audioUrl; //想要播放的音频地址
audioExample.play();
}else{
Toast('语音地址已被摧毁');
}
},
}
};
</script>
node部分:
这里我使用的是express框架搭建的后台
具体的获取前台的请求代码如下
安装multiparty
cnpm install multiparty --save
const express = require('express');
const router = express.Router();
const multiparty = require('multiparty');
const NET_URL = 'http://127.0.0.1:3000/';
router.post('/uploadChatVoice', (req, res, next) => {
let form = new multiparty.Form();
form.uploadDir = 'chatVoiceUpload';
form.parse(req, (err, fields, files) => {
console.log(files, fields)
let chatVoiceUrl = NET_URL + files.chatVoice[0].path.replace(/\\/g, "/");
let chatVoiceTime = fields.voiceTime[0]
console.log(chatVoiceUrl)
if (chatVoiceUrl) {
res.json({
status: 2,
chatVoiceMsg: {
chatVoiceTime,
chatVoiceUrl,
}
})
} else {
res.json({
status: 1,
chatVoiceMsg: {
chatVoiceTime: "",
chatVoiceUrl: ""
}
})
}
//console.log(files)
})
})
在app.js中,定义语音文件路径
app.use('/chatVoiceUpload', express.static('chatVoiceUpload'));
以上就是怎么在Vue中利用node实现音频录制播放功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。