No sound in trimmed & encoded audio blob, Vue 2. Why?
dmitriy-uvin opened this issue · comments
I am trying to cut my mp3 audio in browser and then encode in to blob back and play using blob url, but i receive audio with needed length but without any sound, why so? Need help!
<input type="file" @change="onUploadFile" accept="audio/mpeg, .mp3">
async onUploadFile(event) { const fileData = event.target.files[0]; this.file = fileData; const arrayBuffer = await this.readAudio(fileData); await this.decodeFile(arrayBuffer); }
async readAudio(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = function () { resolve(reader.result); } }); },
`
async decodeFile(arrayBuffer) {
const audioContext = new AudioContext()
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const begin = 5;
const end = 15;
await this.audioBufferSlice(audioBuffer, begin, end);
},
`
async
audioBufferSlice(audioBuffer, begin, end) {
const audioContext = new AudioContext();
const channels = audioBuffer.numberOfChannels;
const rate = audioBuffer.sampleRate;
const duration = audioBuffer.duration;
const startOffset = rate * begin;
const endOffset = rate * end;
const audioLength = endOffset - startOffset;
let trimmedAudio = audioContext.createBuffer(
audioBuffer.numberOfChannels,
audioLength,
audioBuffer.sampleRate
);
for(var i = 0; i < audioBuffer.numberOfChannels; i++){
trimmedAudio.copyToChannel(audioBuffer.getChannelData(i).slice(begin, end), i);
}
let audioData = {
channels: Array.apply(null,{length: trimmedAudio.numberOfChannels})
.map(function(currentElement, index) {
return trimmedAudio.getChannelData(index);
}),
sampleRate: trimmedAudio.sampleRate,
length: trimmedAudio.length,
}
let mp3Data = [];
const sampleBlockSize = 1152;
let mp3encoder = new lamejs.Mp3Encoder(2, audioData.sampleRate, 128);
var left = new Int8Array(audioData.channels[0].length);
var right = new Int8Array(audioData.channels[1].length);
for (var i = 0; i < audioData.channels[0].length; i += sampleBlockSize) {
var leftChunk = left.subarray(i, i + sampleBlockSize);
var rightChunk = right.subarray(i, i + sampleBlockSize);
var mp3buf = await mp3encoder.encodeBuffer(leftChunk, rightChunk);
if (mp3buf.length > 0) {
mp3Data.push(mp3buf);
}
}
let buf = await mp3encoder.flush();
if (buf.length > 0) {
mp3Data.push(buf);
}
var blob = new Blob(mp3Data, {type: 'audio/mp3'});
var url = window.URL.createObjectURL(blob);
console.log('MP3 URl: ', url);
},
`
@zhuker