Vue+node实现音频录制播放功能
程序员文章站
2022-03-13 08:20:40
实现效果:主要实现代码逻辑部分,具体页面结构就不一一介绍了。vue部分:安装recorderxcnpm install recorderx --save 或者npm install recorderx...
实现效果:
主要实现代码逻辑部分,具体页面结构就不一一介绍了。
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实现音频录制播放功能的文章就介绍到这了,更多相关vue 实现音频录制播放内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!