-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
84 lines (72 loc) · 2.52 KB
/
script.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
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
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const playButton = document.getElementById('play');
const downloadButton = document.getElementById('download');
const audio = document.getElementById('audio');
const durationDiv = document.getElementById('duration');
const durationSpan = document.getElementById('durationSpan');
let mediaRecorder;
let audioChunks = [];
let startTime;
let isRecording = false;
startButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
playButton.addEventListener('click', playRecording);
downloadButton.addEventListener('click', downloadRecording);
async function startRecording() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
mediaRecorder.onstart = () => {
startTime = new Date().getTime();
isRecording = true;
durationDiv.style.display = 'block';
updateDuration();
};
mediaRecorder.onstop = () => {
isRecording = false;
durationDiv.style.display = 'none';
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
audio.src = audioUrl;
playButton.disabled = false;
downloadButton.disabled = false;
};
mediaRecorder.start();
startButton.disabled = true;
stopButton.disabled = false;
}
function stopRecording() {
if (isRecording) {
mediaRecorder.stop();
startButton.disabled = false;
stopButton.disabled = true;
durationDiv.style.display = 'none';
audioChunks = [];
}
}
function updateDuration() {
if (isRecording) {
const currentTime = new Date().getTime();
const elapsedTime = new Date(currentTime - startTime);
const minutes = elapsedTime.getUTCMinutes();
const seconds = elapsedTime.getUTCSeconds();
durationSpan.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
setTimeout(updateDuration, 1000);
}
}
function playRecording() {
if (audio.src) {
audio.play();
}
}
function downloadRecording() {
if (audio.src) {
const a = document.createElement('a');
a.href = audio.src;
a.download = 'recorded_audio.wav';
a.click();
}
}