Node.js Express FFMPEG Mp3 Pitch and Tempo Changer Web App Deployed to Heroku Full Project 2020

Node.js Express FFMPEG Mp3 Pitch and Tempo Changer Web App Deployed to Heroku Full Project 2020

 

 

 

Live Demo

 

You can see the live demo of the app right here

 

Get Started

 

In order to get started you need to install these dependencies which are listed below

 

npm init -y

 

npm i express

 

npm i multer

 

npm i nodemon

 

 

Now make the entry level file index.js and start a simple express server on port 3000 like this

 

 

const express = require("express");

const app = express();


const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});


app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

 

Now we will load the index.html for our user so that it can interact with the application. Copy paste the code inside the index.html file

 

 

index.html

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Mp3 Pitch Changer Web App in Node and Express</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <br><br>
          <h1 class="text-center">
              Mp3 Pitch Changer
          </h1>
          <br>
          <form action="/changepitch" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="file" multiple required class="form-control">
            </div>
            <div class="form-group">
              <label for="pitch">Pitch Value:</label>
              <input type="number" step="0.1" class="form-control" name="pitch" required value="1" id="">
            </div>
            <div class="form-group">
              <label for="tempo">Tempo Value:</label>
              <input type="number" step="0.1" class="form-control" name="tempo" required value="0.8" id="">
            </div>
            <div class="form-group">
                <button class="btn btn-danger btn-block">
                    Download MP3
                </button>
            </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>

 

 

 

Creating Uploads Folder Dynamically

 

 

Now we will create the folders dynamically where we will store the mp3 files which will be processed by ffmpeg and then it will be converted to a pitched file

 

 

const fs = require("fs");


var dir = "public";
var subDirectory = "public/uploads";

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);

  fs.mkdirSync(subDirectory);
}

 

See also  Node.js Unit Converter ( Length + Time + Temperature) Example in Javascript Using devs-unit-converter Library Full Project For Beginners

 

 

Here for the very first time the node.js application loads it will check the condition if the folder public doesn’t exist then it will create this folder and also it will create the uploads folder inside the public folder as a subdirectory.

 

 

 

Setting Public Folder as Static

 

 

Now in this block of code we will set the public folder as static so that it can store the mp3 files

 

 

app.use(express.static("public"));

 

 

 

Loading the BodyParser Middleware

 

 

BodyParser middleware is very much necessary for this application as we will processing the form data which is submitted by the user inside the index.html file. So for that you need to copy paste the below code inside index.js

 

 

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

 

 

 

Uploading Mp3 Files to Server Using Multer

 

 

Now the comes the most important part of the application we need to first of all upload the mp3 to the uploads folder before we can process them. So for this we will be using a famous library of node called multer to do this task. Copy paste this block of code to upload files inside node.

 

 

const multer = require("multer");

const path = require('path');


var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});



const audioFilter = function (req, file, cb) {
  // Accept videos only
  if (!file.originalname.match(/\.(mp3)$/)) {
    req.fileValidationError = "Only audio files are allowed!";
    return cb(new Error("Only audio files are allowed!"), false);
  }
  cb(null, true);
};

var upload = multer({ storage: storage, fileFilter: audioFilter });

 

See also  Build a Wikipedia API Search Bar or Engine in Browser Using Javascript Full Project For Beginners

 

 

 

Changing Pitch and Tempo of Mp3

 

 

Now we will do the fun part of the application after we upload the mp3 files on the server. We will issue a simple shell command inside our node.js application using a built in library of node called as child_process. So in this block of code we will use a special ffmpeg command which will carry out this process for us automatically. All this code will be put inside the post request which the user makes inside the index.html form.

 

 

 

app.post("/changepitch", upload.single("file"), (req, res) => {
  pitch = req.body.pitch;
  tempo = req.body.tempo;
  console.log(pitch)
  console.log(tempo)
  if (req.file) {
    exec(
      `ffmpeg -i ${req.file.path} -af asetrate=44100*${pitch},aresample=44100,atempo=${tempo} ${outputFilePath}`,
      (error, stdout, stderr) => {
        if (error) {
          console.log(`error: ${error.message}`);
          return;
        } else {
          console.log("pitch changed successfully of mp3");
          res.download(outputFilePath, (err) => {
            if (err) throw err;

            fs.unlinkSync(req.file.path);

            fs.unlinkSync(outputFilePath);
          });
        }
      }
    );
  }
});

 

 

DOWNLOAD SOURCE CODE

 

Leave a Reply