时间:2021-12-21 10:10:18 | 栏目:vue | 点击:次
实现效果:
主要实现代码逻辑部分,具体页面结构就不一一介绍了。
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'));