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

Detailed explanation of Windows time server configuration method

Recently, I found that the company's server t...

MySQL 8.0.11 Community Green Edition Installation Steps Diagram for Windows

In this tutorial, we use the latest MySQL communi...

Use of TypeScript Generics

Table of contents 1. Easy to use 2. Using generic...

Some suggestions for HTML beginners and novices, experts can ignore them

Feelings: I am a backend developer. Sometimes when...

mysql is not an internal command error solution

The error "mysql is not an internal command&...

Detailed explanation of the implementation of shared modules in Angular projects

Table of contents 1. Shared CommonModule 2. Share...

How to invert the implementation of a Bezier curve in CSS

First, let’s take a look at a CSS carousel animat...

Vue uses v-model to encapsulate the entire process of el-pagination components

Use v-model to bind the paging information object...

43 Web Design Mistakes Web Designers Should Watch Out For

This is an article about website usability. The a...

CSS code for arranging photos in Moments

First, you can open Moments and observe several l...

How to understand SELinux under Linux

Table of contents 1. Introduction to SELinux 2. B...

Summary of SQL deduplication methods

When using SQL to extract data, we often encounte...

React's context and props explained

Table of contents 1. context 1. Usage scenarios 2...