Created
February 28, 2024 12:25
-
-
Save SREENATHPGS/731c74addb5d22350998972a97b58b86 to your computer and use it in GitHub Desktop.
Start / Stop Using Microphone JS Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
</head> | |
<body> | |
<button id = "micButton">Mic</button> | |
<audio id = "localAudio" ></audio> | |
<script> | |
var micButton = undefined; | |
var localAudio = undefined; | |
var recording = false; | |
var media_config = { video: false, audio: true }; | |
let onStreamAvailable = function (stream) { | |
window.localStream = stream; // A | |
}; | |
let onStreamError = function(err) { | |
console.error(`STREAMER-TEST : Error getting media permissions : ${err}`); | |
} | |
function getLocalStream() { | |
if (window.localStream) { | |
return; | |
} | |
console.log('STREAMER-TEST : Starting Stream.'); | |
navigator.mediaDevices.getUserMedia(media_config).then(onStreamAvailable).catch(onStreamError); | |
} | |
var startRecording = function() { | |
console.log('STREAMER-TEST : Starting recording.'); | |
if (!window.localStream) { | |
console.error('STREAMER-TEST : Stream unavailable.'); | |
// return; | |
} | |
getLocalStream(); | |
// window.localStream.getAudioTracks()[0].enabled = true; | |
}; | |
var stopRecording = function() { | |
console.log('STREAMER-TEST : Stopping recording.'); | |
if (!window.localStream) { | |
console.error('STREAMER-TEST : Stream unavailable.'); | |
return; | |
} | |
window.localStream.getTracks().forEach(t => { | |
t.stop(); | |
t.enabled = false; | |
}); | |
window.localStream = undefined; | |
recording = false; | |
}; | |
var buttonClick = function(e) { | |
if (!recording) { | |
recording = true; | |
startRecording(); | |
} else { | |
recording = false; | |
stopRecording(); | |
} | |
}; | |
(function () { | |
micButton = document.getElementById("micButton"); | |
localAudio = document.getElementById("localAudio"); | |
micButton.addEventListener('click', buttonClick); | |
console.log("STREAMER-TEST : DOM Loaded."); | |
getLocalStream(); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment