I am trying to get the sample rate of each chunk of audio recorded using AudioContext but when I run my current code it prints the sample rate once and then keeps printing Uncaught (in promise) DOMException: Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data. Why is this occurring and how can I fix it?
async function getSampleRate() {
try {
const constraints = {
audio: {
channelCount: 1
}
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
mediaRecorder = new MediaRecorder(stream, {
mimeType: 'audio/webm'
});
// Start recording audio
mediaRecorder.start(1000);
// Create an AudioContext object
const audioContext = new(window.AudioContext || window.webkitAudioContext)();
// Function to handle data available
const handleDataAvailable = async(e) => {
// Create a Blob from the received audio data
const audioBlob = new Blob([e.data], {
type: 'audio/webm'
});
// Create a URL for the Blob
const audioURL = URL.createObjectURL(audioBlob);
// Fetch the audio data as an ArrayBuffer
const response = await fetch(audioURL);
const audioArrayBuffer = await response.arrayBuffer();
// Decode the ArrayBuffer into an AudioBuffer
const audioBuffer = await audioContext.decodeAudioData(audioArrayBuffer);
// Extract the sample rate
const sampleRate = audioBuffer.sampleRate;
// Log the sample rate
console.log('Sample Rate:', sampleRate);
};
// Push audio chunks to buffer
mediaRecorder.ondataavailable = handleDataAvailable;
// Stop recording when mediaRecorder stops
mediaRecorder.onstop = () => {
console.log('Recording stopped');
};
} catch (error) {
console.error('Error accessing microphone:', error);
}
}
getSampleRate()