Vue+node realizes audio recording and playback function

Vue+node realizes audio recording and playback function

Result:

insert image description here

The main part is to implement the code logic, and the specific page structure will not be introduced one by one.

Vue part:
Install recorderx

cnpm install recorderx --save

or

npm install recorderx --save

Introduced in a specific component

<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:{
	    	//Recording voice recordingVoice() {
				// that.news_img = !that.news_img
				rc.start()
					.then(() => {
						this.startime = new Date();
					})
					.catch(error => {
						alert("Failed to get microphone");
					});
			  },
			  //Send voice 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.starttime) / 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;
							}
							}
						});
				
			},
			//Play the audio playChatVoice(audio) {
				let audioUrl = audio;
				if(audioUrl){
					
					let audioExample = new Audio();
					audioExample.src = audioUrl; //The audio address you want to play audioExample.play();
				}else{
					Toast('Voice address has been destroyed');
				}
				
			},
	    }
	};
</script>

Node part:
Here I use the express framework to build the background. The specific request code for getting the front end is as follows: Install 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)

  })
})

In app.js, define the voice file path

app.use('/chatVoiceUpload', express.static('chatVoiceUpload')); 

insert image description here

This is the end of this article about Vue+node realizing audio recording and playback functions. For more relevant Vue audio recording and playback content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue carousel component implements $children and $parent and comes with a useful gif recording tool
  • Vue method of recording video and compressing video files
  • How to solve the problem of automatic audio playback and MP3 voice packaging in chrome browser online in vue
  • Solve the problem of switching vue project components and automatically playing audio under ios WeChat

<<:  MySQL 5.7.18 free installation version window configuration method

>>:  Sample code for deploying Spring-boot project with Docker

Recommend

How to calculate the value of ken_len in MySQL query plan

The meaning of key_len In MySQL, you can use expl...

Mysql example of splitting into multiple rows and columns by specific symbols

Some fault code tables use the following design p...

Detailed explanation of Mysql self-join query example

This article describes the Mysql self-join query....

MySQL decimal unsigned update negative numbers converted to 0

Today, when verifying the concurrency problem of ...

Two ways to implement text stroke in CSS3 (summary)

question Recently I encountered a requirement to ...

About Generics of C++ TpeScript Series

Table of contents 1. Template 2. Generics 3. Gene...

A brief discussion on the solution to excessive data in ElementUI el-select

Table of contents 1. Scenario Description 2. Solu...

Vue implements online preview of PDF files (using pdf.js/iframe/embed)

Preface I am currently working on a high-quality ...

The most commonly used HTML tags to create web pages

1. Optimization of commonly used HTML tags HTML s...

Using radial gradient in CSS to achieve card effect

A few days ago, a colleague received a points mal...

Docker binding fixed IP/cross-host container mutual access operation

Preface Previously, static IPs assigned using pip...

SQL implementation of LeetCode (196. Delete duplicate mailboxes)

[LeetCode] 196.Delete Duplicate Emails Write a SQ...