Currently, I have 3 buttons on my webpage - one to start recording audio, one to stop the recording, and one to play the recorded audio. Using MediaRecorder makes it easy to capture audio as a blob data. However, I am facing issues when trying to upload this blob as an audio file to the server. The setup includes an audio element with a file type, a flag indicating if recording is ongoing (0 or 1), and the requirement to upload the blob once the recording stops.
Below is the code snippet:
var thisAudioBlob = document.getElementById("audioElement");
var playFlag = 0;
function initFunction() {
async function getUserMedia(constraints) {
if (window.navigator.mediaDevices) {
return window.navigator.mediaDevices.getUserMedia(constraints);
}
let legacyApi =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (legacyApi) {
return new Promise(function (resolve, reject) {
legacyApi.bind(window.navigator)(constraints, resolve, reject);
return reject('rejected');
});
} else {
// === show an alert
}
}
let audioChunks = [];
let rec;
let blob;
function handlerFunction(stream) {
rec = new MediaRecorder(stream);
rec.start();
rec.ondataavailable = (e) => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
blob = new Blob(audioChunks, { type: "audio/mp3" });
blobUrl = URL.createObjectURL(blob);
document.getElementById("audioElement").src = URL.createObjectURL(blob);
var recordedAudioPath = document.getElementById("audioElement").src;
tempAudioFilePathField.value = recordedAudioPath;
recordedAudioFlag = 1;
}
};
}
function startusingBrowserMicrophone(boolean) {
getUserMedia({ audio: boolean }).then((stream) => {
handlerFunction(stream);
});
}
startusingBrowserMicrophone(true);
myStopButton.addEventListener("click", (e) => {
if (playFlag != 1) {
try {
new File([thisAudioBlob], "audio_temp.mp3", {
type: thisAudioBlob.type,
lastModified:new Date().getTime()
});
} catch(error) {
// === handle error
}
rec.stop();
audioNoteFlagField.value = "1";
} else {
playFlag = 0;
thisAudioBlob.pause();
bulletIconDiv.style.color = "white";
myPlayButton.style.color = "white";
document.getElementById("audioElement").currentTime = 0.01;
audioText.textContent = "Click play to listen...";
try {
new File([thisAudioBlob], "audio_temp.mp3", {
type: thisAudioBlob.type,
lastModified:new Date().getTime()
});
audioSaveAjax();
} catch(error) {
// === handle error
}
}
});
}
function audioSaveAjax() {
var fd = new FormData();
fd.append('fname', 'test_audio_file.mp3');
fd.append('data', thisAudioBlob);
$.ajax({
type: 'POST',
url: ‘get_audio.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// === print message in console
});
}
Unfortunately, I am not able to generate the audio file on the server correctly. Instead of the expected audio file, I only receive a small 25-byte file filled with random characters. What could be causing this issue? Any assistance would be greatly appreciated.