-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVoiceMemo.html
88 lines (71 loc) · 2.76 KB
/
VoiceMemo.html
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎙️</text></svg>" />
<title>Record and Send Voice Memo</title>
</head>
<body>
<div>
<h2>Record a voice memo</h2>
<button id="startBtn">Start Recording</button>
<button id="stopBtn" disabled>Stop Recording</button>
<audio id="audio" controls></audio>
</div>
</body>
<script>
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const audio = document.getElementById('audio');
let recorder;
let audioStream;
function startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
audioStream = stream;
recorder = new MediaRecorder(stream);
const audioChunks = [];
recorder.addEventListener('dataavailable', (event) => {
audioChunks.push(event.data);
});
recorder.addEventListener('stop', () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/mp3' });
const fileName = generateFileName();
sendAudioData(audioBlob, fileName);
const audioUrl = URL.createObjectURL(audioBlob);
audio.src = audioUrl;
audio.controls = true;
});
recorder.start();
startBtn.disabled = true;
stopBtn.disabled = false;
})
.catch(err => console.error(err));
}
function stopRecording() {
recorder.stop();
audioStream.getAudioTracks().forEach(track => track.stop());
startBtn.disabled = false;
stopBtn.disabled = true;
}
function sendAudioData(data, fileName) {
const serverUrl = "PUT HERE YOUR ENDPOINT URL";
const formData = new FormData();
formData.set('file', data, fileName);
fetch(serverUrl, { method: "POST", body: formData})
.then(response => console.log(`Audio data (${fileName}) sent to server.`))
.catch(error => console.error("Error sending audio data to server: ", error));
}
function generateFileName() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const timestamp = date.getTime().toString();
return `${year}-${month}-${day}-${timestamp}.mp3`;
}
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', stopRecording);
</script>
</html>