wav格式base64字符串转成wav文件

NodeJs版

一、wav格式 Base64 转音频 

var fs = require('fs');

(async () => {
    var fileData = fs.readFileSync('./base64.txt', 'utf-8');
    // fileData = fileData.replace(/^data:audio\/\w+;base64,/, "");  // 不做替换也行
    var dataBuffer =  Buffer.from(fileData, 'base64');
    var now = Date.now(); //获取系统当前时间数值
    var savePath = './' + now + '.wav'; //服务器存储文件名

    fs.writeFile(savePath, dataBuffer, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log('成功');
        }
    });
})()

 

二、多段wav格式的Base64 合成一个 wav音频文件

var fs = require('fs');

(async () => {
    var fileData = fs.readFileSync('./voice_base64.txt', 'utf-8');
    // fileData = fileData.replace(/^data:audio\/\w+;base64,/, "");  // 不做替换也行
    var dataBuffer = Buffer.from(fileData, 'base64');
    var now = Date.now(); //获取系统当前时间数值
    var savePath = './' + now + '.wav'; //服务器存储文件名

    //模拟多段wav base64
    var allBuffer = compliteWav([
        dataBuffer,
        dataBuffer,
        dataBuffer
    ])

    fs.writeFile(savePath, allBuffer, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log('成功');
        }
    });
})()


function compliteWav(res) {
    const wavHeadLen = 44;
    let times = res.length;
    let wavData = [];
    let allAudioLen = 0;
    for (let num = 0; num < times; num++) {
        let wav = Buffer.from(res[num], 'base64');
        wavData.push(wav)
        allAudioLen += wav.length;
    }
    let wavHead = wavData[0].slice(0, wavHeadLen)
    //pcm部分
    let pcmLen = allAudioLen - times * wavHeadLen
    let fileLen = pcmLen + wavHeadLen - 8
    //修改4-8字节为<文件长度-4> 小端对齐
    let fileLenBytes = Buffer.allocUnsafe(4);
    fileLenBytes.writeUIntLE(fileLen, 0, 4)
    wavHead = Buffer.concat([wavHead.slice(0, 4), fileLenBytes, wavHead.slice(8)])
    //修改第40-44字节为<文件长度-44>
    let pcmLenBytes = Buffer.allocUnsafe(4);
    pcmLenBytes.writeUIntLE(pcmLen, 0, 4)
    wavHead = Buffer.concat([wavHead.slice(0, 40), pcmLenBytes])

    let wavBytes = wavHead
    for (let num = 0; num < times; num++) {
        let b = wavData[num].slice(wavHeadLen)
        wavBytes = Buffer.concat([wavBytes, b])
    }
    return wavBytes
}

 

wav 与 mp3 的转化使用 ffmpeg 工具

wav转mp3

ffmpeg -i input.wav -f mp3 -acodec libmp3lame -y output.mp3

mp3转wav

ffmpeg -i input.mp3 -f wav output.wav

 

wav文件格式分析与详解

voice_base64.txt

posted @ 2020-07-06 00:28  .追风逐月  阅读(5221)  评论(1编辑  收藏  举报