Vue+node实现音频录制播放功能
作者:Jeslie-He
这篇文章主要介绍了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实现音频录制播放功能的文章就介绍到这了,更多相关Vue 实现音频录制播放内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!