Vue+node實現音訊錄製播放功能
阿新 • • 發佈:2021-03-31
實現效果:
主要實現程式碼邏輯部分,具體頁面結構就不一一介紹了。
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 { d程式設計客棧ata(){ 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 - thttp://www.cppcns.comhis.shttp://www.cppcns.comtartime) / 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 www.cppcns.comchatVoiceUrl = 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: "",chaBBlzKaUtVoiceUrl: "" } }) } //console.log(files) }) })
在app.js中,定義語音檔案路徑
app.use('/chatVoiceUpload',express.static('chatVoiceUpload'));
到此這篇關於Vue+node實現音訊錄製播放功能的文章就介紹到這了,更多相關Vue 實現音訊錄製播放內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!