-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestMedia-2.0.0.js
296 lines (241 loc) · 9.48 KB
/
requestMedia-2.0.0.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
var requestMedia = function(opts){
if (!navigator.mediaDevices.getUserMedia || window.MediaRecorder == undefined){
throw "Not supported on your browser, use the latest version of Firefox or Chrome'";
}
this.defaults = {
preview: null, //HTML5 video/audio element
output: null, //HTML5 video/audio element
onGetPermission: function() {},
onForgetPermission: function() {},
onError: function (err) {console.log(err.name + ': ' + err.message)},
onStartRecording: function() {},
onStopRecording: function() {},
onPictureTaken: function() {},
onDownload: function() {},
audio:true, //can receive an object with audio constraints
video:{ //video constraints
width:{
min:640,
ideal:1280,
max:1080
},
height:{
min:480,
ideal:720,
max:1980
},
frameRate:{
min:24,
ideal:60,
max:120
},
facingMode: "user" //On mobile, defaults to the user facing camera
}
}
for(var i in this.defaults){
this[i] = (opts[i] !== undefined) ? opts[i] : this.defaults[i]
}
this.dataArray = [];
this.stream = null;
this.recorder = null;
this.blob = null;
this.urlobj = null
this.canvas = null;
this.fileName = null;
this.fileType = "video/webm"; //defaults to webm but we switch to mp4 on Safari 14.0.2+
this._getOptionRecorder = function(){
if(typeof MediaRecorder.isTypeSupported === 'function'){
var options = {mimeType: null}
if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
options.mimeType = 'video/webm;codecs=vp9';
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
options.mimeType = 'video/webm;codecs=h264';
} else if (MediaRecorder.isTypeSupported('video/webm')) {
options.mimeType = 'video/webm';
} else if (MediaRecorder.isTypeSupported('video/mp4')) {
//Safari 14.0.2 has an EXPERIMENTAL version of MediaRecorder enabled by default
options.mimeType = 'video/mp4';
}
console.log('Using ' + options.mimeType);
return options;
} else {
return undefined;
}
}
}
requestMedia.prototype.requestPermission = function() {
var that = this;
navigator.mediaDevices.getUserMedia({video: that.video, audio: that.audio}).then(
function(stream){
that.stream = stream;
that.stream.getTracks().forEach(function(track) {
if(track.kind == "audio"){
track.onended = function(event){
console.log("audio track.onended Audio track.readyState="+track.readyState+", track.muted=" + track.muted);
}
}
if(track.kind == "video"){
track.onended = function(event){
console.log("video track.onended Audio track.readyState="+track.readyState+", track.muted=" + track.muted);
}
}
});
if(that.preview && typeof that.preview === "object" && (that.preview.nodeName === "AUDIO" || that.preview.nodeName === "VIDEO")){
that.preview.srcObject = that.stream;
that.preview.play();
}
}).catch(function(err){
if (that.onError && typeof this.onError === 'function'){
that.onError(err)
} else {
console.log('Request access error: ' + err)
}
});
}
requestMedia.prototype.forgetPermission = function() {
if (this.stream == null) return;
this.stream.getTracks().forEach(function(track) {track.stop();});
if (this.onForgetPermission && typeof this.onForgetPermission === 'function'){
this.onForgetPermission();
}
}
requestMedia.prototype.startRecording = function(){
var that = this;
if (that.stream == null) throw "Could not get local stream from mic/camera";
// Reset everything from any previous recordings
that.dataArray = [];
that.fileType = null;
that.blob = null;
that.recorder = null;
that.fileName = null;
console.log('Starting...')
// Get mimeType supported
var mimeType = that._getOptionRecorder();
// Config MediaRecorder with mimeType (if available)
if (!mimeType){
that.recorder = new MediaRecorder(that.stream);
} else {
that.fileType = mimeType.mimeType;
that.recorder = new MediaRecorder(that.stream, mimeType);
}
// Config onDataAvailable event
that.recorder.ondataavailable = function(e) {
console.log('mediaRecorder.ondataavailable, e.data.size='+e.data.size);
if (e.data && e.data.size > 0) {
that.dataArray.push(e.data);
}
};
// Config OnErro event
if (that.onError && typeof that.onError === 'function') {
that.recorder.onerror = that.onError
} else {
that.recorder.onerror = function(e){
console.log('Recording error: ' + e);
};
}
// Config OnStart event
if (that.onStartRecording && typeof that.onStartRecording === 'function') {
that.recorder.onstart = that.onStartRecording();
} else {
that.recorder.onstart = function(){
console.log('Start recording, that.recorder.state = ' + that.recorder.state);
}
}
// Config OnStop event
that.recorder.onstop = function(){
console.log('Stop recording, that.recorder.state = ' + that.recorder.state);
that.blob = new Blob(that.dataArray, {type: that.recorder.mimeType})
if(that.output && typeof that.output === "object" && (that.output.nodeName === "AUDIO" || that.output.nodeName === "VIDEO")){
that.output.src = URL.createObjectURL(that.blob);
that.output.controls = true;
}
switch(that.fileType){
case "video/mp4":
that.fileName = ['file_', (new Date() + '').slice(4, 28), '.mp4'].join('');
break;
default:
that.fileName = ['file_', (new Date() + '').slice(4, 28), '.webm'].join('');
}
}
// Config timeslice for OnDataAvailable as 0.1 sec
that.recorder.start(100);
}
requestMedia.prototype.stopRecording = function() {
var that = this;
that.recorder.stop();
if (that.onStopRecording && typeof that.onStopRecording === 'function') {
//This timeout is here, just to make sure we execute the function after the recorder stoped.
setTimeout(that.onStopRecording(), 500);
}
}
requestMedia.prototype.download = function() {
var that = this;
if (that.onDownload && typeof that.onDownload === 'function') {
that.onDownload();
}
a = document.createElement('a');
a.style = "display: none";
a.download = that.fileName;
if (that.urlobj){
a.href = that.urlobj;
} else {
a.href = URL.createObjectURL(that.blob);
}
a.textContent = that.fileName;
document.body.appendChild(a);
a.click();
setTimeout(function(){
document.body.removeChild(a);
URL.revokeObjectURL(a.href);
}, 500);
}
requestMedia.prototype.startCanvas = function(w){
/*Initiate the canvas object with explicit width and height generated accordingly to width value and aspect ratio of video element.*/
var that = this;
if (that.stream == null) throw "Could not get local stream from mic/camera";
var width = w, height = 0, context = null;
if (that.canvas){
height = that.preview.videoHeight / (that.preview.videoWidth/width);
// if (isNaN(height)) height = width / (4/3);
if (isNaN(height)) height = width * 9/12;
that.canvas.setAttribute('width', width);
that.canvas.setAttribute('height', height);
}
context = that.canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, that.canvas.width, that.canvas.height);
var data = that.canvas.toDataURL('image/png');
that.output.setAttribute('src', data);
}
requestMedia.prototype.takePicture = function () {
/*
From stream object generate image by requested frame moment.
*/
var that = this;
if (that.stream == null) throw "Could not get local stream from mic/camera";
var context = that.canvas.getContext('2d');
if (that.canvas.width && that.canvas.height){
width = that.canvas.width;
height = that.canvas.height;
context.drawImage(that.preview, 0, 0, width, height);
var urlimg = that.canvas.toDataURL('image/png');
that.output.setAttribute('src', urlimg);
that.urlobj = urlimg;
var BASE64_MARKER = ';base64,';
var parts = urlimg.split(BASE64_MARKER);
var content_type = parts[0].split(':')[1];
var filebinary = window.atob(parts[1]);
var filebinary_length = filebinary.length;
var uInt8Array = new Uint8Array(filebinary_length);
for (var i = 0; i < filebinary_length; ++i) {
uInt8Array[i] = filebinary.charCodeAt(i);
}
that.blob = new Blob([uInt8Array], {'type': content_type});
if (that.onPictureTaken && typeof that.onPictureTaken === 'function') {
setTimeout(that.onPictureTaken(), 50);
}
}else{
console.log('erro');
console.log(that.canvas);
}
}