/** * mp3编码 * * @static * @param {dataView} bytes encodePCM的数据 * @param {number} sampleBits 采样位数 * @returns {dataview} MP3数据 */ encodeMP3 = function(bytes, inputSampleRate){ var channels = 1; //1 for mono or 2 for stereo var sampleRate = inputSampleRate; //44.1khz (normal mp3 samplerate) var kbps = 128; //encode 128kbps mp3 var mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, kbps);
var samples = newInt16Array(bytes.buffer); //one second of silence (get your data from the source you have) var sampleBlockSize = 1152; //can be anything but make it a multiple of 576 to make encoders life easier
var mp3Data = []; for (var i = 0; i < samples.length; i += sampleBlockSize) { var sampleChunk = samples.subarray(i, i + sampleBlockSize); mp3buf = mp3encoder.encodeBuffer(sampleChunk); if (mp3buf.length > 0) { mp3Data.push(mp3buf); // fake mp3 fill(0,0,4) } } var mp3buf = mp3encoder.flush(); //finish writing mp3 if (mp3buf.length > 0) { mp3Data.push(newInt8Array(mp3buf)); //fake mp3 } return mp3Data; }