javascript 使用javascript将wav转换为mp3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23676396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:21:29  来源:igfitidea点击:

convert wav to mp3 using javascript

javascripthtml

提问by user3556610

Below is a code, I would like to convert wav format to mp3. Refereed to Record.js. But it is going over my head. Can anyone solve this? (View consists of empty DataView i.e, DataView {})

下面是一个代码,我想将wav格式转换为mp3。参考Record.js。但它正在超越我的头脑。任何人都可以解决这个问题吗?(视图由空的 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;

采纳答案by rafaelcastrocouto

You can use Recordmp3jssince it will give the mp3 audio directly.

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

If you want to understand it, I implemented a very simple version here. Notice that the wavs converted with this implementation need to be mono or the result will be messy.

如果你想理解它,我在这里实现了一个非常简单的版本。请注意,使用此实现转换的 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;
};