'JavaScript: errors when adding 0s (silence) to the begginning and end of audio arrays
I am attempting to add silence before and after an audio file using javascript. My idea was to add zero values at the beginning and end of the audio. both of the methods I tried failed
Method 1, playback audio via AudioContext
const context = new AudioContext()
async function createSoundArray() {
await fetch('file.mp3')
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
const data = audioBuffer.getChannelData(0) // Float32Array(100000)
editAudio(data)
});
}
createSoundArray()
function editAudio(data){
const editedData = []
for(var i = 0; i < data.length + 50000; i++){// adds 25000 0 values (silence) to the begginning and end of array
if( i > 25000 && i <= 125000){
editedData.push(data[i - 25000])
}else{
editedData.push(0)
}
}
console.log(editedData) // array(150000)
const Uint32 = Uint32Array.from(values)
const audioCtx = new AudioContext()
console.log(Uint32.buffer)// ArrayBuffer(150000)
audioCtx.decodeAudioData(pimbo.buffer, function (buf) { //error could not decode
const playback = audioCtx.createBufferSource();
playback.buffer = buf;
playback.connect(audioCtx.destination);
audioCtx.resume()
console.log(playback.buffer)
});
}
This method resulted in the following error:
The buffer passed to decodeAudioData contains an unknown content type.
Method 2, Playback audio via audio element
const context = new AudioContext()
async function createSoundArray() {
await fetch('file.mp3')
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
const data = audioBuffer.getChannelData(0) // Float32Array(100000)
editAudio(data)
});
}
createSoundArray()
function editAudio(data){
const editedData = []
for(var i = 0; i < data.length + 50000; i++){// adds 25000 0 values (silence) to the begginning and end of array
if( i > 25000 && i <= 125000){
editedData.push(data[i - 25000])
}else{
editedData.push(0)
}
}
const blob = new Blob(editedData)
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play()//error no supported source found
}
This method resulted in the following error:
Failed to play audio because no supported source was found
Because Both of these methods failed, this leads me to believe that the zeros added are causing the data to not be recognized as audio. However I don't understand why this is because I am simply adding zeros which are values that already exist inside the audio data before editing it. Does anyone know what I am doing wrong or why this is not working?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|