vakodiya commited on
Commit
8d6648d
1 Parent(s): c68e0fd

Update mic_component.js

Browse files
Files changed (1) hide show
  1. mic_component.js +33 -40
mic_component.js CHANGED
@@ -1,41 +1,34 @@
1
- const recordAudio = () => {
2
- return new Promise(async resolve => {
3
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
4
- const mediaRecorder = new MediaRecorder(stream);
5
- const audioChunks = [];
6
-
7
- mediaRecorder.addEventListener("dataavailable", event => {
8
- audioChunks.push(event.data);
9
- });
10
-
11
- const start = () => mediaRecorder.start();
12
-
13
- const stop = () => {
14
- return new Promise(resolve => {
15
- mediaRecorder.addEventListener("stop", () => {
16
- const audioBlob = new Blob(audioChunks);
17
- const audioUrl = URL.createObjectURL(audioBlob);
18
- const audio = new Audio(audioUrl);
19
- const play = () => audio.play();
20
- resolve({ audioBlob, audioUrl, play });
21
- });
22
-
23
- mediaRecorder.stop();
24
- });
 
 
 
 
 
 
 
25
  };
26
-
27
- resolve({ start, stop });
28
- });
29
- };
30
-
31
- const sleep = time => new Promise(resolve => setTimeout(resolve, time));
32
-
33
- const handleAction = async () => {
34
- const recorder = await recordAudio();
35
- recorder.start();
36
- await sleep(3000);
37
- const audio = await recorder.stop();
38
- audio.play();
39
- };
40
-
41
- document.querySelector("button").addEventListener("click", handleAction);
 
1
+ const recordButton = document.getElementById("recordButton");
2
+ const stopButton = document.getElementById("stopButton");
3
+ const audioChunks = [];
4
+
5
+ let mediaRecorder;
6
+
7
+ navigator.mediaDevices.getUserMedia({ audio: true })
8
+ .then(function(stream) {
9
+ mediaRecorder = new MediaRecorder(stream);
10
+
11
+ recordButton.onclick = function() {
12
+ mediaRecorder.start();
13
+ console.log("Recording started...");
14
+ };
15
+
16
+ stopButton.onclick = function() {
17
+ mediaRecorder.stop();
18
+ console.log("Recording stopped...");
19
+ };
20
+
21
+ mediaRecorder.ondataavailable = function(e) {
22
+ audioChunks.push(e.data);
23
+ };
24
+
25
+ mediaRecorder.onstop = function(e) {
26
+ const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
27
+ const reader = new FileReader();
28
+ reader.readAsDataURL(audioBlob);
29
+ reader.onloadend = function() {
30
+ const base64data = reader.result.split(',')[1];
31
+ Streamlit.setComponentValue(base64data);
32
  };
33
+ };
34
+ });