简体   繁体   中英

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.

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
}

I think the web audio's decodeAudioData is what you are looking for.

You want the PCM data, right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM