forked from mozdevs/MediaRecorder-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
record-live-audio.js
55 lines (46 loc) · 1.79 KB
/
record-live-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
// This example uses MediaRecorder to record from a live audio stream,
// and uses the resulting blob as a source for an audio element.
//
// The relevant functions in use are:
//
// navigator.mediaDevices.getUserMedia -> to get audio stream from microphone
// 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 can use as audio src
var recordButton, stopButton, recorder;
window.onload = function () {
recordButton = document.getElementById('record');
stopButton = document.getElementById('stop');
// get audio stream from user's mic
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function (stream) {
recordButton.disabled = false;
recordButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
recorder = new MediaRecorder(stream);
// listen to dataavailable, which gets triggered whenever we have
// an audio blob available
recorder.addEventListener('dataavailable', onRecordingReady);
});
};
function startRecording() {
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 audio = document.getElementById('audio');
// e.data contains a blob representing the recording
audio.src = URL.createObjectURL(e.data);
audio.play();
}