-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
56 lines (47 loc) · 1.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const startButton = document.getElementById("start-button");
const stopButton = document.getElementById("stop-button");
const volumeInput = document.getElementById("volume");
startButton.addEventListener("click", function () {
startMicrophone();
});
stopButton.addEventListener("click", function () {
stopMicrophone();
});
volumeInput.addEventListener("input", function () {
setVolume(this.value);
});
let audioContext;
let microphone;
let destination;
let gainNode;
function startMicrophone() {
navigator.mediaDevices
.getUserMedia({ audio: true })
.then(function (stream) {
audioContext = new AudioContext();
microphone = audioContext.createMediaStreamSource(stream);
destination = audioContext.destination;
// create a gain node to control the volume
gainNode = audioContext.createGain();
gainNode.gain.value = volumeInput.value;
microphone.connect(gainNode).connect(destination);
})
.catch(function (err) {
console.error("Error accessing microphone:", err);
});
}
function stopMicrophone() {
if (microphone) {
microphone.disconnect();
microphone = null;
}
if (audioContext) {
audioContext.close();
audioContext = null;
}
}
function setVolume(volume) {
if (gainNode) {
gainNode.gain.value = volume;
}
}