forked from mozdevs/MediaRecorder-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
record-video-and-audio.js
62 lines (49 loc) · 1.88 KB
/
record-video-and-audio.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
// This example uses MediaRecorder to record from an audio and video stream, and uses the
// resulting blob as a source for a video element.
//
// The relevant functions in use are:
//
// navigator.mediaDevices.getUserMedia -> to get the video & audio stream from user
// MediaRecorder (constructor) -> create MediaRecorder instance for a stream
// MediaRecorder.ondataavailable -> event to listen to when the recording is ready
// MediaRecorder.start -> start recording
// MediaRecorder.stop -> stop recording (this will generate a blob of data)
// URL.createObjectURL -> to create a URL from a blob, which we use as video src
var recordButton, stopButton, recorder, liveStream;
window.onload = function () {
recordButton = document.getElementById('record');
stopButton = document.getElementById('stop');
// get video & audio stream from user
navigator.mediaDevices.getUserMedia({
audio: true,
video: true
})
.then(function (stream) {
liveStream = stream;
var liveVideo = document.getElementById('live');
liveVideo.src = URL.createObjectURL(stream);
liveVideo.play();
recordButton.disabled = false;
recordButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
});
};
function startRecording() {
recorder = new MediaRecorder(liveStream);
recorder.addEventListener('dataavailable', onRecordingReady);
recordButton.disabled = true;
stopButton.disabled = false;
recorder.start();
}
function stopRecording() {
recordButton.disabled = false;
stopButton.disabled = true;
// Stopping the recorder will eventually trigger the 'dataavailable' event and we can complete the recording process
recorder.stop();
}
function onRecordingReady(e) {
var video = document.getElementById('recording');
// e.data contains a blob representing the recording
video.src = URL.createObjectURL(e.data);
video.play();
}