Search code examples
node.jsaudioffmpegfile-processingraw

How to convert an mp3 file to raw audio format using javascript


I'm working on a project that involves song matching, so I am integrating with rapidApi's shazam endpoints. But the thing is, the song matching endpoint needs the audio snippet to be a base64 string of the audio in raw audio format. I know the API works. I downloaded a 3rd party application to do the conversion from mp3 to .raw, and converted it to base64 before making the request with it.

Now, I need to integrate this flow programmatically. How do I convert an mp3 or any audio source really to a .raw file? I've done a lot of searching but I can't find any solution.


Solution

  • I went with the @ffmpeg/ffmpeg webassembly package. A javascript port of ffmpeg.

    const convertToRaw = async (filePath)=>{
        const ffmpeg = createFFmpeg({ log: true })
        await ffmpeg.load();
        const file = await fetchFile(filePath)
        ffmpeg.FS('writeFile', 'input.mp3', file)
        await ffmpeg.run('-i', 'input.mp3', '-f', 's16le', '-acodec', 'pcm_s16le', '-ac', '1', 'output.raw')
        const data = ffmpeg.FS('readFile', 'output.raw')
        const base64 = Buffer.from(data.buffer).toString('base64')
        return base64
    }