Fullstack alchemy with nextjs and ffmpeg: convert video to audio model

Fullstack alchemy with nextjs and ffmpeg: convert video to audio model

Let’s construct a easy nextjs app which can convert video to audio information and downloads it.
No further backend, VMs or server, every little thing operating on nextjs and could be simply deployed on vercel.

Background Story of our most important parts

  1. Nextjs – A backend (sure, backend) framework developed by vercel which ships react (kinda not precisely) to the browser with so many rendering methods, some good, some extra complicated than F1’s ferrari crew technique. Summing up, actually cool device if you wish to transfer quick and ship manufacturing grade full-stack apps. It comes with in-built assist for creating apis which runs on server surroundings to your consumer with out the additional effort for set backend deployment or these docker containers or lambdas; they in some way mimic ec2 behaviour although.
  2. FFMPEG – Beast device, in all probability one of many largest gigachad stuff obtainable on the web. Officiaily they go along with – An entire, cross-platform resolution to report, convert and stream audio and video.

Let’s start; Try to observe alongside

  1. Create a brand new nextjs app by
npx create-subsequent-app@newest
  1. you may go for customisation
What is your challenge named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` listing? No / Yes
Would you like to use App Router? (advisable) No / Yes
Would you like to customise the default import alias (@/*)? No / Yes
What import alias would you want configured? @/*
  1. For utilizing ffmpeg inside our app, we are going to use fluent-ffmpeg which makes it simpler to create a ffmpeg command in a nodejs like module. They say this on their web page This library abstracts the complicated command-line utilization of ffmpeg right into a fluent, simple to make use of node.js module. https://www.npmjs.com/package deal/fluent-ffmpeg
  2. We may even be utilizing multer for this for importing a file. You can obtain multer from https://www.npmjs.com/package deal/multer
  3. Create an api folder inside app listing and create a folder named convertAudio.ts. Paste the next code there
import multer from "multer";
import { exec } from "child_process";
import { guarantees as fs } from "fs";

const add = multer({ dest: "/tmp" }); 

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async (req, res) => {
  if (req.technique === "POST") {
    const convertAudio = async (filePath: any, outputFormat: any) => {
      return new Promise((resolve, reject) => {
        const outputPath = `/tmp/output.${outputFormat}`;
        exec(`ffmpeg -i ${filePath} ${outputPath}`, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve(outputPath);
          }
        });
      });
    };

    const fileHandlingMiddleware = add.single("audioFile");

    fileHandlingMiddleware(req, res, async (err) => {
      if (err) {
        return res.standing(500).json({ error: "Error importing file." });
      }

      attempt {
        const convertedFilePath = await convertAudio(req.file.path, "mp3"); // Convert to mp3 for this instance
        const fileBuffer = await fs.readFile(convertedFilePath);

        res.setHeader(
          "Content-Disposition",
          "attachment; filename=transformed.mp3"
        );
        res.setHeader("Content-Type", "audio/mp3");
        res.finish(fileBuffer);

        // Cleanup temp information
        await fs.unlink(req.file.path);
        await fs.unlink(convertedFilePath);
      } catch (error) {
        res
          .standing(500)
          .json({ error: "Error changing audio. Some drawback occured" });
      }
    });
  } else {
    res.standing(405).json({ error: "Only POST requests are allowed." });
  }
};

Let’s perceive this code briefly

exec(`ffmpeg -i ${filePath} ${outputPath}`, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve(outputPath);
          }
        });

This will create a ffmpeg command taking authentic file path and an output path to retailer the audio file.

res.setHeader(
          "Content-Disposition",
          "attachment; filename=transformed.mp3"
        );
        res.setHeader("Content-Type", "audio/mp3");
        res.finish(fileBuffer);

This set essential headers ("Content-Disposition",) to the response object to inform the browser to straight obtain the file with the title ("attachment; filename={file_name}").

That’s it, operating your nextjs app will make this api obtainable at /api/convertAudio to your nextjs app which you’ll straight use with a put up request.

Note: This will solely work for form-type multipart/form-data since we’re utilizing multer.

No must setup an surroundings, straight deploy it to vercel and it’ll work wonderful.

That’s one one of the best a part of nextjs is to take away the road or atleast blur between frontend and backend.

Thanks for studying 😄

HI-FI News

through DEV Community https://dev.to

April 21, 2024 at 10:30AM