tchvu3 / capacitor-voice-recorder

Capacitor plugin for voice recording
MIT License
75 stars 61 forks source link

Question : How to truncate the b64 audio ? #22

Closed j-catania closed 1 year ago

j-catania commented 2 years ago

Hello @tchvu3,

We are looking for truncate the generated audio. 🚀

  1. Truncate the B64String directly
    
    const start = result.value.recordDataBase64.slice(
    0,
    delaiSequenceDebut
    );
    const end = result.value.recordDataBase64.slice(
    -delaiSequenceFin
    );

const audioRef = new Audio( data:${result.value.mimeType};base64,${deb+fin} ); audioRef.oncanplaythrough = () => audioRef.play(); audioRef.load();

--> We hear nothing

2. Truncate an ArrayBuffer
```ts
// decoding
const binaryAudio = window.atob(result.value.recordDataBase64);
const lengthBinary = binaryAudio.length;
// To bytes
const byte = new Uint8Array(lengthBinary);
for (let i = 0; i < lengthBinary; i++) {
  byte[i] = binaryAudio.charCodeAt(i);
}
let arrayBuffer = byte.buffer;

// get the first 40%
const delaiSequenceDebut = arrayBuffer.byteLength * 0.4;
let arrayBufferStart = arrayBuffer.slice(
  0,
  delaiSequenceDebut
);

// get the last 45%
const delaiSequenceFin = arrayBuffer.byteLength * 0.45;
let arrayBufferEnd = arrayBuffer.slice(
  -delaiSequenceFin
);

// Concat the 2 previous arrays
const byteStart = new Uint8Array(arrayBufferStart);
const byteStop = new Uint8Array(arrayBufferEnd);
const tmp = new Uint8Array([...byteStart, ...byteStop]);

// convert to b64 
let newRecordDataBase64 = '';
var len = tmp.byteLength;
for (var i = 0; i < len; i++) {
  newRecordDataBase64 += String.fromCharCode(tmp[i]);
}
newRecordDataBase64 = window.btoa(newRecordDataBase64);

// playing the b64
const audioRef = new Audio(
  `data:${result.value.mimeType};base64,${newRecordDataBase64}`
);
audioRef.oncanplaythrough = () => audioRef.play();
audioRef.load();

--> We can hear the start but the ending part is corrupted

Do you kown how can we process this media ?

Thanks a lot, Eddy & Julien

Poke @e-allais