]> git.taranathan.com Git - audio-stream.git/commitdiff
try #1
authorTaran Nathan <moogoesmeow123@gmail.com>
Mon, 20 Jul 2026 23:53:12 +0000 (16:53 -0700)
committerTaran Nathan <moogoesmeow123@gmail.com>
Tue, 21 Jul 2026 03:11:23 +0000 (20:11 -0700)
index.html
script.js

index eafb03cdd77129dda8deff24fd56c53a6e0edfb1..e2cad11c55f1fb672da77869af9d2d1d7e04d7f0 100644 (file)
@@ -12,9 +12,6 @@
 
 <body>
   <img src="/favicon.png" style="width:20%;">
-  <header>
-    <h1>Record and Play Audio in JavaScript</h1>
-  </header>
   <p>
     <button id="btnStart">START RECORDING</button>
     <button id="btnStop" disabled>STOP RECORDING</button>
index 2a8c9147e5815954390a88ba5529969be2362380..553481880a0c92a3bc25415c36e1eef5c30aef5c 100644 (file)
--- a/script.js
+++ b/script.js
@@ -1,10 +1,64 @@
-console.log("wassup")
-// Access the permission for use
-// the microphone
-navigator.mediaDevices.getUserMedia({ audio: true })
-  .then(function(audio_stream) {
-    console.log("hi");
-  })
-  .catch(function(err) {
-    console.log(err.name, err.message);
-  });
+let mediaRecorder;
+let audioChunks = [];
+let recordedAudioUrl = "";
+
+const startButton = document.getElementById("btnStart");
+const stopButton = document.getElementById("btnStop");
+const playButton = document.getElementById("btnPlay");
+const audioElement = document.getElementById("audioPlay");
+
+startButton.addEventListener("click", async () => {
+  try {
+    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+    mediaRecorder = new MediaRecorder(stream);
+    audioChunks = [];
+
+    mediaRecorder.addEventListener("dataavailable", (event) => {
+      if (event.data.size > 0) {
+        audioChunks.push(event.data);
+      }
+    });
+
+    mediaRecorder.addEventListener("stop", async () => {
+      const audioBlob = new Blob(audioChunks, { type: "audio/ogg" });
+      console.log(await audioBlob.text());
+
+      if (recordedAudioUrl) {
+        URL.revokeObjectURL(recordedAudioUrl);
+      }
+
+      recordedAudioUrl = URL.createObjectURL(audioBlob);
+      console.log(recordedAudioUrl);
+      audioElement.src = recordedAudioUrl;
+      playButton.disabled = false;
+
+      stream.getTracks().forEach((track) => track.stop());
+    });
+
+    mediaRecorder.start();
+    startButton.disabled = true;
+    stopButton.disabled = false;
+    playButton.disabled = true;
+  } catch (error) {
+    console.error("Microphone access failed:", error);
+  }
+});
+
+stopButton.addEventListener("click", () => {
+  if (!mediaRecorder || mediaRecorder.state !== "recording") {
+    return;
+  }
+
+  mediaRecorder.stop();
+  stopButton.disabled = true;
+  startButton.disabled = false;
+});
+
+playButton.addEventListener("click", () => {
+  if (!recordedAudioUrl) {
+    return;
+  }
+
+  audioElement.currentTime = 0;
+  audioElement.play();
+});