Comments (8)
FloatArray2Int16 (floatbuffer) {
var int16Buffer = new Int16Array(floatbuffer.length);
for (var i = 0, len = floatbuffer.length; i < len; i++) {
if (floatbuffer[i] < 0) {
int16Buffer[i] = 0x8000 * floatbuffer[i];
} else {
int16Buffer[i] = 0x7FFF * floatbuffer[i];
}
}
return int16Buffer;
}
you can change float32array to int16array.
and call encodeMono function like this
let blob = this.encodeMono(channels, sampleRate, int16Buffer);
encodeMono function is same as here.
https://github.com/zhuker/lamejs/blob/master/example.html
from lamejs.
Here's my suggestion for converting any Web Audio API-supported media to MP3 using the AudioContext
to decode the source media.
This approach is versatile and can also be applied to various video formats as needed.
const fetchAudio = async (url: string) => {
const response = await fetch(url, {
mode: 'cors',
referrerPolicy: 'no-referrer-when-downgrade',
});
const arrayBuffer = await response.arrayBuffer();
const audioContext = new AudioContext();
const buffer = await audioContext.decodeAudioData(arrayBuffer);
return buffer;
};
// Do something to get the url and setup your s3
fetchAudio(url).then((data) => {
const binary = audioToMp3Binary(data);
s3.send(new PutObjectCommand({
Bucket: bucketName,
Key: `test/${fileName}`,
Body: binary, // Uint8Array
}));
});
The AudioBuffer
encapsulates the channel data within a Float32Array
, alongside the sampleRate
attribute for reference.
import lamejs from 'lamejs';
import MPEGMode from 'lamejs/src/js/MPEGMode';
import Lame from 'lamejs/src/js/Lame';
import BitStream from 'lamejs/src/js/BitStream';
(window as any).MPEGMode = MPEGMode;
(window as any).Lame = Lame;
(window as any).BitStream = BitStream;
export function audioToMp3Binary(audioData: AudioBuffer, debug = true) {
const encoder = new lamejs.Mp3Encoder(1, audioData.sampleRate, 128);
const leftChannel = audioData.getChannelData(0);
// Interpolate to -32768 to 32767, which is signed int16
const interpolated = leftChannel.map((n) =>
Math.max(-32768, Math.min(32768, n * (n < 0 ? 32768 : 32767)))
);
const int16arr = new Int16Array(leftChannel.length);
// Type coercion, float -> int
interpolated.forEach((n, i) => (int16arr[i] = n));
const mp3Data: Int8Array[] = [];
const sampleBlockSize = 1152;
for (let i = 0; i < int16arr.length; i += sampleBlockSize) {
const sampleChunk = int16arr.subarray(i, i + sampleBlockSize);
const mp3buf = encoder.encodeBuffer(sampleChunk);
if (mp3buf.length > 0) mp3Data.push(mp3buf);
}
mp3Data.push(new Int8Array(encoder.flush())); // Fill gaps in mp3buf
if (debug) debugDownload(mp3Data);
return int8ArrayToUint8Array(mp3Data);
}
For debugging purposes, you can download the file using a Blob
with the MIME type audio/mp3
.
function debugDownload(mp3Data: Int8Array[]) {
const blob = new Blob(mp3Data, { type: 'audio/mp3' });
const mp3Url = URL.createObjectURL(blob);
const link = Object.assign(document.createElement('a'), {
href: mp3Url,
download: 'output.mp3',
});
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Finally, should you require the raw binary data, such as for uploading to an S3 bucket, the conversion process would be as follows:
function int8ArrayToUint8Array(int8s: Int8Array[]) {
const totalLength = int8s.reduce((acc, value) => acc + value.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const int8 of int8s) {
result.set(int8, offset);
offset += int8.length;
}
return result;
}
from lamejs.
What kind of data is in your array? You need to use encoder (i.e. Lame) if you have uncompressed audio data there.
You don't need to compile anything to use lamejs.lame.min.js
is already compiled. Just include it in your project and it's good to go.
from lamejs.
The data is in an Float32Array, uncompressed. I used lame but when i tried to run the application i get an error for files creted when installing lame (haven't modified them )
from lamejs.
@zero41120 Getting silence using your solution in an AudioWorklet
. What is the significance of MPEGMode
, Lame
, and BitStream
?
from lamejs.
@zero41120 Getting silence using your solution in an
AudioWorklet
. What is the significance ofMPEGMode
,Lame
, andBitStream
?
from lamejs.
@zero41120 That still doesn't tell me what the significance of MPEGMode
, Lame
, and BitStream
are.
from lamejs.
@zero41120 That still doesn't tell me what the significance of
MPEGMode
,Lame
, andBitStream
are.
The three variables has no significance for developer perspective and exist solely to satisfy TypeScript's requirements for referencing them as they would in JavaScript, due to their global nature on window. LameJS, not being TypeScript-based and without @types definitions, necessitates their presence to prevent TypeScript calling them undefined
.
from lamejs.
Related Issues (20)
- lamejs not working with angular 8 -- Uncaught ReferenceError: Lame is not defined HOT 3
- Silent MP3 file when converting output from Azure Speech-to-Text javascript SDK HOT 2
- Is it possible to use VBR (variable bit rate) HOT 1
- Blob to MP3 HOT 1
- lamejs.WavHeader.readHeader - Uncaught (in promise) TypeError: Cannot read property 'dataOffset' of undefined HOT 3
- There is a problem with the sound quality in the node environment
- Deleted
- recorder wavdata to mp3 causes ui rendering block HOT 2
- window not defined
- "MPEGMode is not defined" HOT 21
- [Firefox] Data from right channel is not passed to encoder despite there are expected two channels
- MPEGMode is not defined HOT 5
- No sound in trimmed & encoded audio blob, Vue 2. Why?
- wav转mp3的时候lampjs报"ReferenceError: MPEGMode is not defined" HOT 11
- Cannot read properties of undefined (reading 'println') HOT 1
- can i convert amr to mp3?
- License clarification
- zhuker/lamejs 打包报错 HOT 1
- Why does this code work on Firefox not on Chromium?
- Maintainer needed?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from lamejs.