使用javascript将wav转换为mp3

时间:2014-05-15 11:03:30

标签: javascript html5

下面是一个代码,我想将wav formate转换为mp3。提到Record.js。但这是我的头脑。谁能解决这个问题? (View包含空DataView,即DataView {})

var blob = new Blob ( [ view ], { type : 'audio/wav' } );

    // let's save it locally
    outputElement.innerHTML = 'Handing off the file now...';
    var url = (window.URL || window.webkitURL).createObjectURL(blob);
    var link = window.document.createElement('a');
    link.href = url;
    link.download = 'output.wav';
    var click = document.createEvent("Event");
    click.initEvent("click", true, true);
    link.dispatchEvent(click);
    audioplayer.src = url;

1 个答案:

答案 0 :(得分:6)

您可以使用 Recordmp3js ,因为它会直接提供mp3音频。

如果你想了解它,我实现了一个非常简单的版本 here 。请注意,使用此实现转换的wav需要是单声道或结果将是混乱的。

var convert = function(){
    var arrayBuffer = this.result;
    var buffer = new Uint8Array(arrayBuffer);

    data = parseWav(buffer);

    var config = {
      mode : 3,
      channels:1,
      samplerate: data.sampleRate,
      bitrate: data.bitsPerSample
    };

    var mp3codec = Lame.init();
    Lame.set_mode(mp3codec, config.mode || Lame.JOINT_STEREO);
    Lame.set_num_channels(mp3codec, config.channels || 2);
    Lame.set_num_samples(mp3codec, config.samples || -1);
    Lame.set_in_samplerate(mp3codec, config.samplerate || 44100);
    Lame.set_out_samplerate(mp3codec, config.samplerate || 44100);
    Lame.set_bitrate(mp3codec, config.bitrate || 128);    
    Lame.init_params(mp3codec);

    var array = Uint8ArrayToFloat32Array(data.samples);

    var mp3data = Lame.encode_buffer_ieee_float(mp3codec, array, array);

    var url = 'data:audio/mp3;base64,'+encode64(mp3data.data);
    convertedPlayer.src = url;
    convertedLink.href = url;

    var name = file.name.substr(0, file.name.lastIndexOf('.'));
    convertedLink.textContent = name + '.mp3';

    converted.style.display = 'block';

    Lame.encode_flush(mp3codec);
    Lame.close(mp3codec);
    mp3codec = null;
};