var micEl; let chunks = []; var mediaRecorder = false; var sendFile = async function (blob) { const formData = new FormData(); formData.append('userfile', blob, new Date() + ".webm"); const response = await fetch('upload.php', { method: 'POST', body: formData }); return response.json() } var initRecording = function (autostart) { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { console.info("getUserMedia supported."); navigator.mediaDevices .getUserMedia({ audio: true }) .then((stream) => { mediaRecorder = new MediaRecorder(stream); console.log(mediaRecorder.mimeType); console.log("should i autostarty", autostart); mediaRecorder.ondataavailable = (e) => { chunks.push(e.data); }; mediaRecorder.onstop = (e) => { console.log("got a call to stop"); var audioEl = document.querySelectorAll("audio")[0]; const blob = new Blob(chunks, { type: mediaRecorder.mimeType }); console.log(blob); chunks = []; const audioURL = window.URL.createObjectURL(blob); audioEl.src = audioURL; console.log(audioEl.src); sendFile(blob).then((data) => { document.querySelector(".fn-error").textContent = data }); } if (autostart) { mediaRecorder.start(); } }) } else { console.error("not supported"); } } var startRecording = function (e) { if (!mediaRecorder) { console.log("did not initalise"); initRecording(true); e.currentTarget.setAttribute("active", true); } else { if (mediaRecorder.state === "recording") { console.log("recording was already happening") mediaRecorder.stop(); e.currentTarget.setAttribute("active", false); } else { console.log("not yet recording, about tos tart"); mediaRecorder.start(); e.currentTarget.setAttribute("active", true); } } } window.onload = function () { console.log("load app"); micEl = document.querySelector('.fn-start-recording'); micEl.addEventListener('click', startRecording); }