summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorilotterytea <iltsu@alright.party>2024-06-16 02:25:23 +0500
committerilotterytea <iltsu@alright.party>2024-06-16 02:25:23 +0500
commit5bb3f74b909d4d1eed8635ff4b9b9d383bf0abb2 (patch)
tree440fe47381e76ae4b6b410dbe609b7d06c8780b8
parent9a5cdeba44779ec0c6c297e917a8d4ae0ede70ab (diff)
feat: listen microphone and show dB level
-rw-r--r--index.html2
-rw-r--r--scripts/microphone.js29
-rw-r--r--scripts/volume_processor.js27
3 files changed, 58 insertions, 0 deletions
diff --git a/index.html b/index.html
index 7bc5381..436c7c4 100644
--- a/index.html
+++ b/index.html
@@ -4,5 +4,7 @@
</head>
<body>
<h1>hello, world!</h1>
+ <p id="volume">0 dB</p>
</body>
+ <script src="scripts/microphone.js"></script>
</html> \ No newline at end of file
diff --git a/scripts/microphone.js b/scripts/microphone.js
new file mode 100644
index 0000000..7e8de6a
--- /dev/null
+++ b/scripts/microphone.js
@@ -0,0 +1,29 @@
+if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
+ const volumeHtml = document.getElementById("volume");
+
+ navigator.mediaDevices.getUserMedia({ audio: true })
+ .then(stream => {
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
+ const source = audioContext.createMediaStreamSource(stream);
+
+ audioContext.audioWorklet.addModule("scripts/volume_processor.js")
+ .then(() => {
+ const volumeNode = new AudioWorkletNode(audioContext, "volume_processor");
+ source.connect(volumeNode).connect(audioContext.destination);
+
+ volumeNode.port.onmessage = (event) => {
+ const volume = event.data;
+ const db = 20 * Math.log10(volume);
+
+ volumeHtml.innerHTML = `${db.toFixed(2)} dB`;
+ };
+ }).catch((err) => {
+ console.log(err);
+ })
+ })
+ .catch(err => {
+ console.error('The following getUserMedia error occurred: ' + err);
+ });
+} else {
+ console.warn('getUserMedia not supported on your browser!');
+} \ No newline at end of file
diff --git a/scripts/volume_processor.js b/scripts/volume_processor.js
new file mode 100644
index 0000000..9765e7b
--- /dev/null
+++ b/scripts/volume_processor.js
@@ -0,0 +1,27 @@
+class VolumeProcessor extends AudioWorkletProcessor {
+ constructor() {
+ super();
+ this.volume = 0;
+ }
+
+ process(inputs) {
+ const input = inputs[0];
+ if (input.length > 0) {
+ const channelData = input[0];
+ let sum = 0;
+
+ for (let i = 0; i < channelData.length; i++) {
+ sum += channelData[i] * channelData[i];
+ }
+
+ this.volume = Math.sqrt(sum / channelData.length);
+
+ // Отправляем громкость в основной поток
+ this.port.postMessage(this.volume);
+ }
+
+ return true;
+ }
+}
+
+registerProcessor('volume_processor', VolumeProcessor);