let rec; let gumStream; let captureTimeout; function streaming() { const audioContext = new(window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000, }); let arr = []; navigator.mediaDevices.getUserMedia({ audio: true }) .then((stream) => { const audioSource = audioContext.createMediaStreamSource(stream); gumStream = stream; let stop = false; let input = audioContext.createMediaStreamSource(stream); // Added 'let' to declare 'input' // Create the Recorder object and configure to record mono sound (1 channel) // Recording 2 channels will double the file size rec = new Recorder(input, { numChannels: 1 }); // Start the recording process rec.record(); // Start capturing audio asynchronously captureAndSendAudio(); }) .catch((error) => { console.error('Error accessing microphone:', error); }); } function floatTo16BitPCM(output, offset, input) { for (var i = 0; i < input.length; i++, offset += 2) { var s = Math.max(-1, Math.min(1, input[i])); output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } function captureAndSendAudio() { rec.getBuffer((buffers) => { const float32Array = buffers[0]; rec.clear(); const flatArray = Array.prototype.slice.call(float32Array); if (flatArray.length > 0) { var buffer = new ArrayBuffer(float32Array.length * 2); var view = new DataView(buffer); floatTo16BitPCM(view, 0, float32Array); var byteArray = []; for (var i = 0; i < view.byteLength; i++) { byteArray.push(view.getUint8(i)); } sendMicChunkToDart(byteArray); } }); captureTimeout = setTimeout("captureAndSendAudio()", 200); } function sendMicChunkToDart(array) { window.parent.postMessage({ type: 'micChunk', array: array }, '*'); } function stopRecording() { clearTimeout(captureTimeout); try{ rec.clear(); rec.stop(); gumStream.getAudioTracks()[0].stop(); }catch(e){} window.parent.postMessage({ type: 'micStop' }, '*'); } function checkMicPermission(){ // Check if the browser supports the microphone API. if (navigator.mediaDevices === undefined) { throw new Error('Browser does not support microphone API'); } // Check if the user has granted permission to use the microphone. navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => { // The user has granted permission. }).catch((error) => { // The user has denied permission. }); var retVal = true; // Request permission to use the microphone. navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => { // The user has granted permission. retVal = true; }).catch((error) => { if (error.name === 'PermissionDeniedError') { // The user has denied permission. } retVal = false; }); return retVal; }