How to change mp3 file to wav file in node.js

3 min read 07-10-2024
How to change mp3 file to wav file in node.js


Converting MP3 to WAV in Node.js: A Simple Guide

Want to convert your MP3 files to WAV format using Node.js? This guide will provide you with a straightforward solution using the popular lamejs library.

The Challenge: Converting Audio Formats

MP3 and WAV are two common audio formats, each with its own advantages and disadvantages. MP3 is known for its smaller file size and efficient compression, making it ideal for streaming and storage. However, WAV is favored for its high fidelity and lossless quality, often used for professional audio production and editing.

This article aims to provide a simple solution for converting your MP3 files to WAV using Node.js.

Setting up Your Project

To begin, you'll need to set up your Node.js project and install the lamejs library. You can do this with the following command:

npm install lamejs

Code Implementation

Here's a basic example of how to convert an MP3 file to WAV using lamejs:

const lamejs = require('lamejs');

const fs = require('fs');

// Function to convert MP3 to WAV
async function convertMp3ToWav(inputMp3Path, outputWavPath) {
  try {
    const mp3Buffer = fs.readFileSync(inputMp3Path);
    const mp3Decoder = new lamejs.Mp3Decoder();
    const mp3Data = mp3Decoder.decodeBuffer(mp3Buffer);

    // Create a new buffer to store WAV data
    const wavBuffer = Buffer.alloc(mp3Data.length * 2); // Each sample in WAV is 2 bytes
    let offset = 0;

    // Convert MP3 data to WAV format
    for (let i = 0; i < mp3Data.length; i++) {
      // Convert from 16-bit signed integer to 32-bit float
      const sample = mp3Data[i] / 32768;

      // Write the sample to the WAV buffer (stereo)
      wavBuffer.writeFloatLE(sample, offset);
      wavBuffer.writeFloatLE(sample, offset + 4); // Duplicate for stereo

      offset += 8;
    }

    // Write the WAV data to the output file
    fs.writeFileSync(outputWavPath, wavBuffer);

    console.log(`MP3 converted to WAV successfully!`);
  } catch (error) {
    console.error("Error converting MP3 to WAV:", error);
  }
}

// Example usage:
convertMp3ToWav('input.mp3', 'output.wav'); 

Explanation:

  1. Import lamejs and fs: Import the necessary libraries to decode MP3 data and interact with the file system.
  2. Read MP3 file: Read the contents of your MP3 file into a buffer using fs.readFileSync.
  3. Decode MP3 data: Use the lamejs decoder to decode the MP3 data into an array of samples.
  4. Create WAV buffer: Allocate a new buffer to store the WAV data. Since each WAV sample is represented by 2 bytes (16-bit), the buffer size should be twice the length of the MP3 data.
  5. Convert samples: Iterate through the decoded MP3 samples and convert each one to a 32-bit float value (representing audio amplitude).
  6. Write WAV data: Write the converted samples to the WAV buffer, ensuring a stereo format (writing each sample twice).
  7. Save WAV file: Use fs.writeFileSync to save the WAV data to the specified output file.

Additional Considerations

  • Error handling: Implement comprehensive error handling to ensure graceful failure in case of problems during the conversion process.
  • Stereo/Mono: The provided example assumes stereo audio. If your MP3 file is mono, you'll need to adjust the code to write each sample only once to the WAV buffer.
  • Bit depth: The code currently outputs a WAV file with 32-bit floating-point samples. You can adjust the conversion process to output different bit depths if required.
  • Alternative libraries: While lamejs is a popular choice for MP3 decoding, you can explore other libraries like ffmpeg or node-fluent-ffmpeg for more advanced features and flexibility.

Conclusion

This article provided a straightforward guide to converting MP3 files to WAV format using Node.js and the lamejs library. By following these steps, you can easily convert your audio files for various purposes, including professional audio production, editing, or compatibility with specific applications.

Remember to always back up your original files before making any changes.

Further exploration:

  • lamejs Documentation: Explore the official documentation for a deeper understanding of the lamejs library and its capabilities.
  • Node.js Documentation: Get familiar with the fundamental concepts of Node.js and its built-in modules, including fs.
  • FFmpeg: Consider exploring the ffmpeg command-line tool for advanced audio and video processing.