const endpoints = 'https://api.alabiabot.com/media/audio/stt';
let content = 'Envie um arquivo ou clique no microfone'; let mr = null; let stream = null; let recording = false;
const getData = function (url, callback) { let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function () { let status = xhr.status; if (status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); };
const createRecorder = function () { navigator.mediaDevices.getUserMedia({ audio: true }).then( stream => { stream = stream; if (MediaRecorder === undefined) { content = 'Seu navegador não suporta o gravador de áudio'; return; } mr = new MediaRecorder(stream); let chunks = []; mr.ondataavailable = data => { chunks.push(data.data); }; mr.onstop = () => { convert(new File(chunks, 'audio.webm')); }; }, err => { content = 'Não conseguimos acessar o seu microfone'; } ); }
const convert = function (file) { let xhr = new XMLHttpRequest(); let resultField = document.getElementById("response");
const data = new FormData(); data.set('file', file);
xhr.open('POST', endpoints, true); xhr.responseType = "json";
xhr.onload = function () { if (xhr.status === 200) { if (xhr.response !== null) { resultField.value = xhr.response.results[0].text; } } else { alert('Request failed. Returned status of ' + xhr.status); } }; xhr.send(data); }
const onFileChange = function (event) { for (let i = 0; i < event.target.files.length; i += 1) { convert(event.target.files[i]); } }; const startMicrofone = function () { try { mr.start(); } catch (error) { return false; } return true; }; const stopMicrofone = function () { try { mr.stop(); } catch (error) { content = error; } createRecorder(); }; const toggleMicrofone = function () { let action = document.getElementById("action"); if (recording) { stopMicrofone(); recording = false; action.innerHTML = "Gravar"; } else { recording = startMicrofone(); action.innerHTML = "Gravando..."; } }; window.onload = function () { if ( navigator.mediaDevices == undefined || navigator.mediaDevices.getUserMedia == null ) { content = 'null'; return; } createRecorder(); }