forked from streamproc/MediaStreamRecorder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MediaStreamRecorder.js
1782 lines (1444 loc) · 54.6 KB
/
MediaStreamRecorder.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Last time updated at September 19, 2015
// links:
// Open-Sourced: https://github.com/streamproc/MediaStreamRecorder
// https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js
// https://www.WebRTC-Experiment.com/MediaStreamRecorder.js
// npm install msr
// updates?
/*
-. this.recorderType = StereoAudioRecorder;
*/
//------------------------------------
// Browsers Support::
// Chrome (all versions) [ audio/video separately ]
// Firefox ( >= 29 ) [ audio/video in single webm/mp4 container or only audio in ogg ]
// Opera (all versions) [ same as chrome ]
// Android (Chrome) [ only video ]
// Android (Opera) [ only video ]
// Android (Firefox) [ only video ]
// Microsoft Edge (Only Audio & Gif)
//------------------------------------
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
//------------------------------------
'use strict';
// ______________________
// MediaStreamRecorder.js
function MediaStreamRecorder(mediaStream) {
if (!mediaStream) {
throw 'MediaStream is mandatory.';
}
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
this.start = function(timeSlice) {
// Media Stream Recording API has not been implemented in chrome yet;
// That's why using WebAudio API to record stereo audio in WAV format
var Recorder = IsChrome || IsEdge || IsOpera ? window.StereoAudioRecorder || IsEdge || IsOpera : window.MediaRecorderWrapper;
// video recorder (in WebM format)
if (this.mimeType.indexOf('video') !== -1) {
Recorder = IsChrome || IsEdge || IsOpera ? window.WhammyRecorder : window.MediaRecorderWrapper;
}
// video recorder (in GIF format)
if (this.mimeType === 'image/gif') {
Recorder = window.GifRecorder;
}
// allows forcing StereoAudioRecorder.js on Edge/Firefox
if (this.recorderType) {
Recorder = this.recorderType;
}
mediaRecorder = new Recorder(mediaStream);
mediaRecorder.blobs = [];
var self = this;
mediaRecorder.ondataavailable = function(data) {
mediaRecorder.blobs.push(data);
self.ondataavailable(data);
};
mediaRecorder.onstop = this.onstop;
mediaRecorder.onStartedDrawingNonBlankFrames = this.onStartedDrawingNonBlankFrames;
// Merge all data-types except "function"
mediaRecorder = mergeProps(mediaRecorder, this);
mediaRecorder.start(timeSlice);
};
this.onStartedDrawingNonBlankFrames = function() {};
this.clearOldRecordedFrames = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.clearOldRecordedFrames();
};
this.stop = function() {
if (mediaRecorder) {
mediaRecorder.stop();
}
};
this.ondataavailable = function(blob) {
console.log('ondataavailable..', blob);
};
this.onstop = function(error) {
console.warn('stopped..', error);
};
this.save = function(file, fileName) {
if (!file) {
if (!mediaRecorder) {
return;
}
var bigBlob = new Blob(mediaRecorder.blobs, {
type: mediaRecorder.blobs[0].type || this.mimeType
});
invokeSaveAsDialog(bigBlob);
return;
}
invokeSaveAsDialog(file, fileName);
};
this.pause = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.pause();
console.log('Paused recording.', this.mimeType || mediaRecorder.mimeType);
};
this.resume = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.resume();
console.log('Resumed recording.', this.mimeType || mediaRecorder.mimeType);
};
this.recorderType = null; // StereoAudioRecorder || WhammyRecorder || MediaRecorderWrapper || GifRecorder
// Reference to "MediaRecorder.js"
var mediaRecorder;
}
// ______________________
// MultiStreamRecorder.js
function MultiStreamRecorder(mediaStream) {
if (!mediaStream) {
throw 'MediaStream is mandatory.';
}
var self = this;
var isFirefox = !!navigator.mozGetUserMedia;
this.stream = mediaStream;
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
this.start = function(timeSlice) {
audioRecorder = new MediaStreamRecorder(mediaStream);
videoRecorder = new MediaStreamRecorder(mediaStream);
audioRecorder.mimeType = 'audio/ogg';
videoRecorder.mimeType = 'video/webm';
for (var prop in this) {
if (typeof this[prop] !== 'function') {
audioRecorder[prop] = videoRecorder[prop] = this[prop];
}
}
audioRecorder.ondataavailable = function(blob) {
if (!audioVideoBlobs[recordingInterval]) {
audioVideoBlobs[recordingInterval] = {};
}
audioVideoBlobs[recordingInterval].audio = blob;
if (audioVideoBlobs[recordingInterval].video && !audioVideoBlobs[recordingInterval].onDataAvailableEventFired) {
audioVideoBlobs[recordingInterval].onDataAvailableEventFired = true;
fireOnDataAvailableEvent(audioVideoBlobs[recordingInterval]);
}
};
videoRecorder.ondataavailable = function(blob) {
if (isFirefox) {
return self.ondataavailable({
video: blob,
audio: blob
});
}
if (!audioVideoBlobs[recordingInterval]) {
audioVideoBlobs[recordingInterval] = {};
}
audioVideoBlobs[recordingInterval].video = blob;
if (audioVideoBlobs[recordingInterval].audio && !audioVideoBlobs[recordingInterval].onDataAvailableEventFired) {
audioVideoBlobs[recordingInterval].onDataAvailableEventFired = true;
fireOnDataAvailableEvent(audioVideoBlobs[recordingInterval]);
}
};
function fireOnDataAvailableEvent(blobs) {
recordingInterval++;
self.ondataavailable(blobs);
}
videoRecorder.onstop = audioRecorder.onstop = function(error) {
self.onstop(error);
};
if (!isFirefox) {
// to make sure both audio/video are synced.
videoRecorder.onStartedDrawingNonBlankFrames = function() {
videoRecorder.clearOldRecordedFrames();
audioRecorder.start(timeSlice);
};
videoRecorder.start(timeSlice);
} else {
videoRecorder.start(timeSlice);
}
};
this.stop = function() {
if (audioRecorder) {
audioRecorder.stop();
}
if (videoRecorder) {
videoRecorder.stop();
}
};
this.ondataavailable = function(blob) {
console.log('ondataavailable..', blob);
};
this.onstop = function(error) {
console.warn('stopped..', error);
};
this.pause = function() {
if (audioRecorder) {
audioRecorder.pause();
}
if (videoRecorder) {
videoRecorder.pause();
}
};
this.resume = function() {
if (audioRecorder) {
audioRecorder.resume();
}
if (videoRecorder) {
videoRecorder.resume();
}
};
var audioRecorder;
var videoRecorder;
var audioVideoBlobs = {};
var recordingInterval = 0;
}
// _____________________________
// Cross-Browser-Declarations.js
// WebAudio API representer
if (typeof AudioContext !== 'undefined') {
if (typeof webkitAudioContext !== 'undefined') {
/*global AudioContext:true*/
var AudioContext = webkitAudioContext;
}
if (typeof mozAudioContext !== 'undefined') {
/*global AudioContext:true*/
var AudioContext = mozAudioContext;
}
}
if (typeof URL !== 'undefined' && typeof webkitURL !== 'undefined') {
/*global URL:true*/
var URL = webkitURL;
}
var IsEdge = navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveBlob || !!navigator.msSaveOrOpenBlob);
var IsOpera = !!window.opera || navigator.userAgent.indexOf('OPR/') !== -1;
var IsChrome = !IsEdge && !IsEdge && !!navigator.webkitGetUserMedia;
if (typeof navigator !== 'undefined') {
if (typeof navigator.webkitGetUserMedia !== 'undefined') {
navigator.getUserMedia = navigator.webkitGetUserMedia;
}
if (typeof navigator.mozGetUserMedia !== 'undefined') {
navigator.getUserMedia = navigator.mozGetUserMedia;
}
} else {
/*global navigator:true */
var navigator = {
getUserMedia: {}
};
}
if (typeof webkitMediaStream !== 'undefined') {
var MediaStream = webkitMediaStream;
}
// Merge all other data-types except "function"
function mergeProps(mergein, mergeto) {
mergeto = reformatProps(mergeto);
for (var t in mergeto) {
if (typeof mergeto[t] !== 'function') {
mergein[t] = mergeto[t];
}
}
return mergein;
}
function reformatProps(obj) {
var output = {};
for (var o in obj) {
if (o.indexOf('-') !== -1) {
var splitted = o.split('-');
var name = splitted[0] + splitted[1].split('')[0].toUpperCase() + splitted[1].substr(1);
output[name] = obj[o];
} else {
output[o] = obj[o];
}
}
return output;
}
// "dropFirstFrame" has been added by Graham Roth
// https://github.com/gsroth
function dropFirstFrame(arr) {
arr.shift();
return arr;
}
function invokeSaveAsDialog(file, fileName) {
if (!file) {
throw 'Blob object is required.';
}
if (!file.type) {
file.type = 'video/webm';
}
var fileExtension = file.type.split('/')[1];
if (fileName && fileName.indexOf('.') !== -1) {
var splitted = fileName.split('.');
fileName = splitted[0];
fileExtension = splitted[1];
}
var fileFullName = (fileName || (Math.round(Math.random() * 9999999999) + 888888888)) + '.' + fileExtension;
if (typeof navigator.msSaveOrOpenBlob !== 'undefined') {
return navigator.msSaveOrOpenBlob(file, fileFullName);
} else if (typeof navigator.msSaveBlob !== 'undefined') {
return navigator.msSaveBlob(file, fileFullName);
}
var hyperlink = document.createElement('a');
hyperlink.href = URL.createObjectURL(file);
hyperlink.target = '_blank';
hyperlink.download = fileFullName;
if (!!navigator.mozGetUserMedia) {
hyperlink.onclick = function() {
(document.body || document.documentElement).removeChild(hyperlink);
};
(document.body || document.documentElement).appendChild(hyperlink);
}
var evt = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(evt);
if (!navigator.mozGetUserMedia) {
URL.revokeObjectURL(hyperlink.href);
}
}
function bytesToSize(bytes) {
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) {
return '0 Bytes';
}
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
// ______________ (used to handle stuff like http://goo.gl/xmE5eg) issue #129
// ObjectStore.js
var ObjectStore = {
AudioContext: window.AudioContext || window.webkitAudioContext
};
// ______________ (used to handle stuff like http://goo.gl/xmE5eg) issue #129
// ObjectStore.js
var ObjectStore = {
AudioContext: window.AudioContext || window.webkitAudioContext
};
// ==================
// MediaRecorder.js
/**
* Implementation of https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html
* The MediaRecorder accepts a mediaStream as input source passed from UA. When recorder starts,
* a MediaEncoder will be created and accept the mediaStream as input source.
* Encoder will get the raw data by track data changes, encode it by selected MIME Type, then store the encoded in EncodedBufferCache object.
* The encoded data will be extracted on every timeslice passed from Start function call or by RequestData function.
* Thread model:
* When the recorder starts, it creates a "Media Encoder" thread to read data from MediaEncoder object and store buffer in EncodedBufferCache object.
* Also extract the encoded data and create blobs on every timeslice passed from start function or RequestData function called by UA.
*/
function MediaRecorderWrapper(mediaStream) {
// if user chosen only audio option; and he tried to pass MediaStream with
// both audio and video tracks;
// using a dirty workaround to generate audio-only stream so that we can get audio/ogg output.
if (this.type === 'audio' && mediaStream.getVideoTracks && mediaStream.getVideoTracks().length && !navigator.mozGetUserMedia) {
var context = new AudioContext();
var mediaStreamSource = context.createMediaStreamSource(mediaStream);
var destination = context.createMediaStreamDestination();
mediaStreamSource.connect(destination);
mediaStream = destination.stream;
}
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
// starting a recording session; which will initiate "Reading Thread"
// "Reading Thread" are used to prevent main-thread blocking scenarios
this.start = function(mTimeSlice) {
mTimeSlice = mTimeSlice || 1000;
isStopRecording = false;
function startRecording() {
if (isStopRecording) {
return;
}
if (isPaused) {
setTimeout(startRecording, 500);
return;
}
mediaRecorder = new MediaRecorder(mediaStream);
mediaRecorder.ondataavailable = function(e) {
console.log('ondataavailable', e.data.type, e.data.size, e.data);
// mediaRecorder.state === 'recording' means that media recorder is associated with "session"
// mediaRecorder.state === 'stopped' means that media recorder is detached from the "session" ... in this case; "session" will also be deleted.
if (!e.data.size) {
console.warn('Recording of', e.data.type, 'failed.');
return;
}
// at this stage, Firefox MediaRecorder API doesn't allow to choose the output mimeType format!
var blob = new window.Blob([e.data], {
type: e.data.type || self.mimeType || 'audio/ogg' // It specifies the container format as well as the audio and video capture formats.
});
// Dispatching OnDataAvailable Handler
self.ondataavailable(blob);
};
mediaRecorder.onstop = function(error) {
// for video recording on Firefox, it will be fired quickly.
// because work on VideoFrameContainer is still in progress
// https://wiki.mozilla.org/Gecko:MediaRecorder
// self.onstop(error);
};
// http://www.w3.org/TR/2012/WD-dom-20121206/#error-names-table
// showBrowserSpecificIndicator: got neither video nor audio access
// "VideoFrameContainer" can't be accessed directly; unable to find any wrapper using it.
// that's why there is no video recording support on firefox
// video recording fails because there is no encoder available there
// http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp#317
// Maybe "Read Thread" doesn't fire video-track read notification;
// that's why shutdown notification is received; and "Read Thread" is stopped.
// https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html#error-handling
mediaRecorder.onerror = function(error) {
console.error(error);
self.start(mTimeSlice);
};
mediaRecorder.onwarning = function(warning) {
console.warn(warning);
};
// void start(optional long mTimeSlice)
// The interval of passing encoded data from EncodedBufferCache to onDataAvailable
// handler. "mTimeSlice < 0" means Session object does not push encoded data to
// onDataAvailable, instead, it passive wait the client side pull encoded data
// by calling requestData API.
mediaRecorder.start(0);
// Start recording. If timeSlice has been provided, mediaRecorder will
// raise a dataavailable event containing the Blob of collected data on every timeSlice milliseconds.
// If timeSlice isn't provided, UA should call the RequestData to obtain the Blob data, also set the mTimeSlice to zero.
setTimeout(function() {
mediaRecorder.stop();
startRecording();
}, mTimeSlice);
}
// dirty workaround to fix Firefox 2nd+ intervals
startRecording();
};
var isStopRecording = false;
this.stop = function() {
isStopRecording = true;
if (self.onstop) {
self.onstop({});
}
};
var isPaused = false;
this.pause = function() {
if (!mediaRecorder) {
return;
}
isPaused = true;
if (mediaRecorder.state === 'recording') {
mediaRecorder.pause();
}
};
this.resume = function() {
if (!mediaRecorder) {
return;
}
isPaused = false;
if (mediaRecorder.state === 'paused') {
mediaRecorder.resume();
}
};
this.ondataavailable = this.onstop = function() {};
// Reference to itself
var self = this;
if (!self.mimeType && !!mediaStream.getAudioTracks) {
self.mimeType = mediaStream.getAudioTracks().length && mediaStream.getVideoTracks().length ? 'video/webm' : 'audio/ogg';
}
// Reference to "MediaRecorderWrapper" object
var mediaRecorder;
}
// ======================
// StereoAudioRecorder.js
function StereoAudioRecorder(mediaStream) {
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
this.start = function(timeSlice) {
timeSlice = timeSlice || 1000;
mediaRecorder = new StereoAudioRecorderHelper(mediaStream, this);
mediaRecorder.record();
timeout = setInterval(function() {
mediaRecorder.requestData();
}, timeSlice);
};
this.stop = function() {
if (mediaRecorder) {
mediaRecorder.stop();
clearTimeout(timeout);
}
};
this.pause = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.pause();
};
this.resume = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.resume();
};
this.ondataavailable = function() {};
// Reference to "StereoAudioRecorder" object
var mediaRecorder;
var timeout;
}
// ============================
// StereoAudioRecorderHelper.js
// source code from: http://typedarray.org/wp-content/projects/WebAudioRecorder/script.js
function StereoAudioRecorderHelper(mediaStream, root) {
// variables
var deviceSampleRate = 44100; // range: 22050 to 96000
if (!ObjectStore.AudioContextConstructor) {
ObjectStore.AudioContextConstructor = new ObjectStore.AudioContext();
}
// check device sample rate
deviceSampleRate = ObjectStore.AudioContextConstructor.sampleRate;
var leftchannel = [];
var rightchannel = [];
var scriptprocessornode;
var recording = false;
var recordingLength = 0;
var volume;
var audioInput;
var sampleRate = root.sampleRate || deviceSampleRate;
var context;
var numChannels = root.audioChannels || 2;
this.record = function() {
recording = true;
// reset the buffers for the new recording
leftchannel.length = rightchannel.length = 0;
recordingLength = 0;
};
this.requestData = function() {
if (isPaused) {
return;
}
if (recordingLength === 0) {
requestDataInvoked = false;
return;
}
requestDataInvoked = true;
// clone stuff
var internalLeftChannel = leftchannel.slice(0);
var internalRightChannel = rightchannel.slice(0);
var internalRecordingLength = recordingLength;
// reset the buffers for the new recording
leftchannel.length = rightchannel.length = [];
recordingLength = 0;
requestDataInvoked = false;
// we flat the left and right channels down
var leftBuffer = mergeBuffers(internalLeftChannel, internalRecordingLength);
var rightBuffer = mergeBuffers(internalLeftChannel, internalRecordingLength);
// we interleave both channels together
if (numChannels === 2) {
var interleaved = interleave(leftBuffer, rightBuffer);
} else {
var interleaved = leftBuffer;
}
// we create our wav file
var buffer = new ArrayBuffer(44 + interleaved.length * 2);
var view = new DataView(buffer);
// RIFF chunk descriptor
writeUTFBytes(view, 0, 'RIFF');
view.setUint32(4, 44 + interleaved.length * 2, true);
writeUTFBytes(view, 8, 'WAVE');
// FMT sub-chunk
writeUTFBytes(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
// stereo (2 channels)
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 4, true);
view.setUint16(32, numChannels * 2, true);
view.setUint16(34, 16, true);
// data sub-chunk
writeUTFBytes(view, 36, 'data');
view.setUint32(40, interleaved.length * 2, true);
// write the PCM samples
var lng = interleaved.length;
var index = 44;
var volume = 1;
for (var i = 0; i < lng; i++) {
view.setInt16(index, interleaved[i] * (0x7FFF * volume), true);
index += 2;
}
// our final binary blob
var blob = new Blob([view], {
type: 'audio/wav'
});
console.debug('audio recorded blob size:', bytesToSize(blob.size));
root.ondataavailable(blob);
};
this.stop = function() {
// we stop recording
recording = false;
this.requestData();
audioInput.disconnect();
};
function interleave(leftChannel, rightChannel) {
var length = leftChannel.length + rightChannel.length;
var result = new Float32Array(length);
var inputIndex = 0;
for (var index = 0; index < length;) {
result[index++] = leftChannel[inputIndex];
result[index++] = rightChannel[inputIndex];
inputIndex++;
}
return result;
}
function mergeBuffers(channelBuffer, recordingLength) {
var result = new Float32Array(recordingLength);
var offset = 0;
var lng = channelBuffer.length;
for (var i = 0; i < lng; i++) {
var buffer = channelBuffer[i];
result.set(buffer, offset);
offset += buffer.length;
}
return result;
}
function writeUTFBytes(view, offset, string) {
var lng = string.length;
for (var i = 0; i < lng; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
// creates the audio context
var context = ObjectStore.AudioContextConstructor;
// creates a gain node
ObjectStore.VolumeGainNode = context.createGain();
var volume = ObjectStore.VolumeGainNode;
// creates an audio node from the microphone incoming stream
ObjectStore.AudioInput = context.createMediaStreamSource(mediaStream);
// creates an audio node from the microphone incoming stream
var audioInput = ObjectStore.AudioInput;
// connect the stream to the gain node
audioInput.connect(volume);
/* From the spec: This value controls how frequently the audioprocess event is
dispatched and how many sample-frames need to be processed each call.
Lower values for buffer size will result in a lower (better) latency.
Higher values will be necessary to avoid audio breakup and glitches
Legal values are 256, 512, 1024, 2048, 4096, 8192, and 16384.*/
var bufferSize = root.bufferSize || 2048;
if (root.bufferSize === 0) {
bufferSize = 0;
}
if (context.createJavaScriptNode) {
scriptprocessornode = context.createJavaScriptNode(bufferSize, numChannels, numChannels);
} else if (context.createScriptProcessor) {
scriptprocessornode = context.createScriptProcessor(bufferSize, numChannels, numChannels);
} else {
throw 'WebAudio API has no support on this browser.';
}
bufferSize = scriptprocessornode.bufferSize;
console.debug('using audio buffer-size:', bufferSize);
var requestDataInvoked = false;
// sometimes "scriptprocessornode" disconnects from he destination-node
// and there is no exception thrown in this case.
// and obviously no further "ondataavailable" events will be emitted.
// below global-scope variable is added to debug such unexpected but "rare" cases.
window.scriptprocessornode = scriptprocessornode;
if (numChannels === 1) {
console.debug('All right-channels are skipped.');
}
var isPaused = false;
this.pause = function() {
isPaused = true;
};
this.resume = function() {
isPaused = false;
};
// http://webaudio.github.io/web-audio-api/#the-scriptprocessornode-interface
scriptprocessornode.onaudioprocess = function(e) {
if (!recording || requestDataInvoked || isPaused) {
return;
}
var left = e.inputBuffer.getChannelData(0);
leftchannel.push(new Float32Array(left));
if (numChannels === 2) {
var right = e.inputBuffer.getChannelData(1);
rightchannel.push(new Float32Array(right));
}
recordingLength += bufferSize;
};
volume.connect(scriptprocessornode);
scriptprocessornode.connect(context.destination);
}
// ===================
// WhammyRecorder.js
function WhammyRecorder(mediaStream) {
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
this.start = function(timeSlice) {
timeSlice = timeSlice || 1000;
mediaRecorder = new WhammyRecorderHelper(mediaStream, this);
for (var prop in this) {
if (typeof this[prop] !== 'function') {
mediaRecorder[prop] = this[prop];
}
}
mediaRecorder.record();
timeout = setInterval(function() {
mediaRecorder.requestData();
}, timeSlice);
};
this.stop = function() {
if (mediaRecorder) {
mediaRecorder.stop();
clearTimeout(timeout);
}
};
this.clearOldRecordedFrames = function() {
if (mediaRecorder) {
mediaRecorder.clearOldRecordedFrames();
}
};
this.pause = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.pause();
};
this.resume = function() {
if (!mediaRecorder) {
return;
}
mediaRecorder.resume();
};
this.ondataavailable = function() {};
// Reference to "WhammyRecorder" object
var mediaRecorder;
var timeout;
}
// ==========================
// WhammyRecorderHelper.js
function WhammyRecorderHelper(mediaStream, root) {
this.record = function(timeSlice) {
if (!this.width) {
this.width = 320;
}
if (!this.height) {
this.height = 240;
}
if (this.video && this.video instanceof HTMLVideoElement) {
if (!this.width) {
this.width = video.videoWidth || video.clientWidth || 320;
}
if (!this.height) {
this.height = video.videoHeight || video.clientHeight || 240;
}
}
if (!this.video) {
this.video = {
width: this.width,
height: this.height
};
}
if (!this.canvas || !this.canvas.width || !this.canvas.height) {
this.canvas = {
width: this.width,
height: this.height
};
}
canvas.width = this.canvas.width;
canvas.height = this.canvas.height;
// setting defaults
if (this.video && this.video instanceof HTMLVideoElement) {
this.isHTMLObject = true;
video = this.video.cloneNode();
} else {
video = document.createElement('video');
video.src = URL.createObjectURL(mediaStream);
video.width = this.video.width;
video.height = this.video.height;
}
video.muted = true;
video.play();
lastTime = new Date().getTime();
whammy = new Whammy.Video();
console.log('canvas resolutions', canvas.width, '*', canvas.height);
console.log('video width/height', video.width || canvas.width, '*', video.height || canvas.height);
drawFrames();
};
this.clearOldRecordedFrames = function() {
whammy.frames = [];
};
var requestDataInvoked = false;
this.requestData = function() {
if (isPaused) {
return;
}
if (!whammy.frames.length) {
requestDataInvoked = false;
return;
}
requestDataInvoked = true;
// clone stuff
var internalFrames = whammy.frames.slice(0);