mic-0.1
by velo_ninja
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microphone Activation</title>
</head>
<body>
<h1>Microphone Activation</h1>
<button id="requestPermissionButton">Request Microphone Permission</button>
<button id="startButton" disabled>Start Microphone</button>
<button id="stopButton" disabled>Stop Microphone</button>
<script>
document.addEventListener('DOMContentLoaded', () => {
const requestPermissionButton = document.getElementById('requestPermissionButton');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
let stream;
let audioContext;
let audioSource;
requestPermissionButton.addEventListener('click', async () => {
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
handleSuccess(stream);
} catch (error) {
console.error('Error accessing microphone:', error);
}
});
startButton.addEventListener('click', () => {
// Use the existing stream if available or request a new one
if (stream) {
handleSuccess(stream);
} else {
requestPermissionButton.click(); // Trigger permission request
}
});
stopButton.addEventListener('click', () => {
if (stream) {
stopMicrophone();
}
});
function handleSuccess(audioStream) {
// Do something with the audio stream, e.g., process or play it.
console.log('Microphone access successful:', audioStream);
audioContext = new (window.AudioContext || window.webkitAudioContext)();
audioSource = audioContext.createMediaStreamSource(audioStream);
// Connect the audio source to the audio context's destination (speakers)
audioSource.connect(audioContext.destination);
// Update UI
...